sort函数
在做算法题时,遇到排序问题,一般都会想到的是冒泡排序,然后他的时间复杂度和空间复杂度太高了,为O(n^2),这个时候就可以用到algorithm库的sort函数了
cmp函数
定义cmp函数,这是一个bool类型的函数,我们必须定义然后在sort函数中使用才能排序
注意:!!! sort函数的升序降序排序是在cmp函数中定义的!!!
如果x>y,返回的是true则代表降序排序
如果x>y,返回的是false则代表的是升序排序
#include<iostream>
#include<algorithm>
using namespace std;
bool cmp(int x,int y){
if(x>y) return true;
return false;
}
调用sort函数排序
向sort()函数中传参,参数对象是要排序的数组或者结构体等
sort(函数首地址,函数末尾地址,cmp)
如果cmp函数在定义时没有问题,那么你的排序就完成了
#include<iostream>
#include<algorithm>
using namespace std;
bool cmp(int x,int y){
if(x>y) return true;
return false;
}
int main(){
int num[]={1,4,2,7,3};
sort(num,num+5,cmp);
return 0;
}