[C++] Detailed explanation of sort function

1. The sort() function is a sorting function in the C++ standard library, and the header file is algorithm
2. Time complexity of the sort() function:
The time complexity of the bubble sorting and selection sorting we are most familiar with is too high and cannot satisfy the requirements we write. needs of the question. The sorting method of the sort function is similar to the quick sort method, and the time complexity is n*log2(n)
3. The parameters of the sort() function
are sort (start address, end address, comparator);
the comparator can be omitted, and the default is ascending order.

int arr[10]={
    
    5,3,6,0,2,8,2,6,9,11};
sort(arr,arr+10);

Writing method with comparator (the comparator can be written according to its own needs, when it returns true):

//首先我们要写一个bool类型的方法,用来返回参数的比较结果
//当比较器返回true时,第一个参数放在前面,第二个参数放在后面,即位置不变
//当比较器返回false时,为两元素交换位置
//这里要注意对参数相等时的处理
//因为可能会在两者相等的时候交换位置,在一些特定的环境下会导致题解出错
//比较器最好写成static函数
//比较器的值可以使用引用类型,节省空间开销
static bool cmp1(int &lhs,int &rhs)//升序
{
    
    
	return lhs<rhs;
}
static bool cmp2(int &lhs,int &rhs)//降序
{
    
    
	return lhs>rhs;
}
sort(arr,arr+10,cmp1);//升序
sort(arr,arr+10,cmp1);//降序

4. Sort the vector

vector<int> vec={
    
    5,3,6,0,2,8,2,6,9,11};
//比较器同对数组排序
sort(vec.begin(),vec.end(),cmp1);
sort(vec.begin(),vec.end(),cmp2);

5. Sort the map.
Note here that the map function has an automatic sorting function by key value (descending order).

typedef pair<int,int> PAIR;
//比较器
//按value值进行降序排序,value值相等key小的在前
static bool cmp_value(const PAIR& lhs,const PAIR& rhs)
{
    
    
	if(lhs.second == rhs.second)
	{
    
    
		return lhs.key<rhs,second;
	}
	return lhs.second > rhs.second;
}
sort(m.begin(),m,end(),cmp_value);

6. Do not use handwritten cmp function

The third parameter of the sortt function can use such a statement to tell the program the sorting principle you adopt:
less<data type>()//Sort from small to large
greater<data type>()//Sort from large to small

sort(arr,arr+10,less<int>());

7. Comparator in lamdba form

//lamdba形式
[](int &a,int &b){
    
    return a<b;}

//使用:
sort(arr,arr+10,[](int &a,int &b){
    
    return a<b;});

Guess you like

Origin blog.csdn.net/qq_45972928/article/details/123442472