# Qsort

int a[] = {4,1,2,3,5,7,6};
qsort(a,7,sizeof(a[0]));

//结果：1 2 3 4 5 6 7

struct node{
int id,num;
}a[6] = {{1,3},{2,4},{3,1},{4,2},{5,6},{6,5}};

int cmp(const void *a,const void *b){
node *aa = (node *)a;
node *bb = (node *)b;
if(aa->num == bb->num){
return aa->id < bb->id;
}
return aa->num > bb->num;    //按num值升序排序
}

qsort(a,6,sizeof(a[0]),cmp);

# Sort

1 int a[] = {4,1,2,3,5,6};
2 sort(a,a+6);
3
4 //排序结果: 1 2 3 4 5 6

 1 struct node{
2     int id,num;
3
4     //重载比较符
5     bool operator < (const node &b) const{
6         if(num == b.num){
7             return id < b.id;
8         }
9         return num > b.num;
10     }
11 }a[6] = {{1,3},{2,4},{3,1},{4,2},{5,6},{6,5}};
12
13
14 //编写比较函数
15 int cmp(node &a,node &b){
16     if(a.num == b.num){
17         return a.id < b.id;
18     }
19     return a.num > b.num;
20 }
21
22 sort(a,a+6);    //重载比较符
23 sort(a,a+6,cmp);    //编写比较函数

 1 //编写仿函数
2 class CMP{
3     public:
4         CMP(int _id,int _num):id(_id),num(_num){}
5         int id;
6         int num;
7         bool operator < (const node &b) const{
8             if(num == b.num){
9                 return id < b.id;
10             }
11             return num > b.num;
12         }
13 };
14
15 vector<CMP>a;
16 sort(a,a+6);

# Stable_sort

1 string s[4] = {"spring","lip","eye","winter"};
2
3 bool cmp(string a, string b){
4     return a.size() < b.size();
5 }
6
7 sort(s,s+4,cmp);

# Partial_sort

int a[] = {6,5,4,3,2,1};
partial_sort(a,a+3,a+6);

//排序结果: 1 2 3 6 5 4

# List::sort

1 list<int>a;
2 a.sort();

posted @ 2018-08-02 11:38  Xenny  阅读(1115)  评论(0编辑  收藏