C語言
void qsort( 待排序數組首地址 , 數組中待排序元素數量 , 各元素的佔用空間大小 , cmp(const void*,const void*) );
頭文件: #include<stdlib.h>
C++
void sort( 待排序數組首地址 , 數組首地址+數組長度 , cmp );
頭文件: #include<algorithm>
一般類型
1.qsort
cmp函數原理(以int類型爲例):
bool cmp(const void *a,const void *b )
{
return *(int *)a-*(int *b); //降序排列
//等同於 return *(int *)a>*(int *b);
}
當函數返回值>0 a 排在 b 前
當函數返回值<0 b 排在 a 前
int,char ,double 等簡單類型的
bool cmp(const void *a,const void *b )
{
return *(int *)a-*(int *b); //降序排列
/********
(int *)爲強制類型轉換
根據需要改寫
*********/
}
2.sort
bool cmp( int &a ,int &b)
{
return a>b;
}
/*char double float...也可以*/
結構體類型
1.sort
一級結構體
struct node{
int x;
char y;
//方法一:
bool operator <(const node &a) //運算符重載
{
return x>a.x; //降序排列
}
//方法二:
bool operator <(const node &a, const node &b)
{
return a.y>b.y;
}
};
vector<node> v;
sort( v.begin(),v.end() );
//方法三
bool cmp(node &a,node &b)
{
return a.x>b.x;
}
vector<node> v;
sort( v.begin(),v.end(),cmp );
二級結構體
struct node
{
int num;
int id;
};
bool cmp(node &a,node &b)
{
if(a.num!=b.num)
return a.num>b.num; //num大的在前
else
return a.id<b.id; //num相同的,id小的在前
}
sort( , , cmp );
2.qsort
struct node{
int id;
int flag;
int pos;
};
//一級結構體比較
bool cmp1(const void *a,const void *b)
{
return (*(struct node *)a).pos>(*(struct node *)b).pos?1:0; //從小到大排序
}
int cmp2(const void *a,const void *b)
{
return (*(struct node *)a).id-(*(struct node *)b).id;
}
//二級結構體比較
int cmp1(const void *a,const void *b)
{
if((*(struct node *)a).pos!=(*(struct node *)b).pos)
return (*(struct node *)a).pos-(*(struct node *)b).pos; //從小到大排序
else
return (*(struct node *)a).id-(*(struct node *)b).id; //pos 相等的 比較 id
}
3.sort 和 qsort 皆可
可以直接調用庫函數 #include<functional>
實現x == y的函數對象 (類模板) |
|
實現x != y的函數對象 (類模板) |
|
實現x > y的函數對象 (類模板) |
|
實現x < y的函數對象 (類模板) |
|
實現x >= y的函數對象 (類模板) |
|
實現x <= y的函數對象 (類模板) |
字符串類型的
struct node {
char str[100];
int num;
};
int cmp1(const void *a, const void *b)
{
return strcmp((struct node *)a->str,(struct node *)b->str;
}
qsort( , , , cmp);
若c++中爲string 類型數據則直接使用大於小於即可