Sort function in C++

Bubble sort is inefficient, so it’s not as good as using the simple sort function

Sort function

#include < algorithm > takes three arguments: sort (a,b,c) a: The first is the starting address of the array to be sorted. B: The second is the end address (the last bit of address to sort). C: The third parameter is the sorting method.

The following specific use of sort () function combination of array sort to do a description!

1. If there is no third argument, sort defaults to small to large
#include<iostream>
#include<algorithm>
using namespace std;
int main(a)
{
 int a[10] = {9.6.3.8.5.2.7.4.1.0};
 for(int i=0; i<10; i++) cout<<a[i]<<endl;sort(a,a+10);  
 for(int i=0; i<10; i++) cout<<a[i]<<endl;return 0;
}
Copy the code
2. The third argument to sort

Less < data type >() // Sort from smallest to largest

#include<iostream>
#include<algorithm>
using namespace std;
int main(a)
{
 int a[10] = {9.6.3.8.5.2.7.4.1.0};
 for(int i=0; i<10; i++) cout<<a[i]<<endl;sort(a,a+10,less<int> ());for(int i=0; i<10; i++) cout<<a[i]<<endl;return 0;
}

Copy the code

Greater < data type >() // Sort from largest to smallest

#include<iostream>
#include<algorithm>
using namespace std;
int main(a)
{
 int a[10] = {9.6.3.8.5.2.7.4.1.0};
 for(int i=0; i<10; i++) cout<<a[i]<<endl;sort(a,a+10,greater<int> ());for(int i=0; i<10; i++) cout<<a[i]<<endl;return 0;
}

Copy the code
3. Use the sort function to sort characters
#include<iostream>
#include<algorithm>
using namespace std;
int main(a)
{
 char a[11] ="asdfghjklk";
 for(int i=0; i<10; i++) cout<<a[i]<<endl;sort(a,a+10,greater<char> ());for(int i=0; i<10; i++) cout<<a[i]<<endl;return 0;
}
Copy the code