Still using bubble sort? Come and understand the sort function

The sort function in C++

The efficiency of bubble sort is low, so it seems that it is not as good as we use the simple and easy-to-operate sort function

sort sort function

Must have header files: #include <algorithm>
has three parameters: sort (a, b, c)
a: the first is the starting address of the array to be sorted.
b: The second is the ending address (the last address to be sorted).
c: The third parameter is the sorting method.

Here is an explanation of using the sort() function to sort the array!

1. If the sort function does not have the third parameter, the default implementation is from small to large
#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
    
    
 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;
}
2. The third parameter of the sort function

less<data type>() //Sort from small to large

#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
    
    
 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;
}

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

#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
    
    
 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;
}

3. Use the sort function to sort characters
#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
    
    
 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;
}

Guess you like

Origin blog.csdn.net/qq_51808107/article/details/111216621