//挺有收获的
//qsort Demo #include <iostream> #include <cstdlib> //qsort #include <cstring> using namespace std; int cmp_int(const void *a,const void *b) { return *(int *)a - *(int *)b; } int cmp_char(const void *a,const void *b) { return *(char *)a - *(char *)b; } int cmp_string(const void *a,const void *b) { return strcmp((char*)a,(char *)b); } struct Node { int x,y; }; int cmp_struct1(const void *a,const void *b) //对结构体一级排序(按结构体中的某个关键字排序) { return (*(Node*)a).x > (*(Node*)b).x ? 1 :-1; } int cmp_struct2(const void *a,const void *b) //对结构体二级排序(按照x从小到大比较 , { //当x相等时按y从大到小比较) struct Node *c = (Node *)a; struct Node *d = (Node *)b; if(c->x!=d->x) return c->x - d->x; else return c->y - d->y; } int main() { //测试qsort对整数排序 int arr[6] = {5,3,12,8,1,9}; qsort(arr,6,sizeof(int),cmp_int); for(int i=0;i<6;i++) { cout<<arr[i]<<" "; } cout<<endl; //测试qsort对char进行排序 char ch[6] = {'v','a','w','k','z','c'}; qsort(ch,6,sizeof(char),cmp_char); for(int i=0;i<6;i++) { cout<<ch[i]<<" "; } cout<<endl; //测试qsort对字符串排序 char str[100][10]= {"abc","cdf","ckg","mvc","java","oracle"}; qsort(str,6,sizeof(str[0]),cmp_string); for(int i=0;i<6;i++) { cout<<str[i]<<" "; } cout<<endl; //测试qsort对结构体的一级排序 (按x域的大小排的顺序) struct Node node[100] ={ {12,15},{30,25}, {20,8},{28,10}, {35,5} ,{30,10} }; qsort(node,6,sizeof(node[0]),cmp_struct1); for(int i=0;i<6;i++) { cout<<node[i].x<<" "<<node[i].y<<"\t"; } cout<<endl; //测试qsort对结构体的二级排序 struct Node node2[100] ={ {12,15},{30,25}, {20,16},{20,10}, {35,5} ,{30,10}, {32,6},{35,50} }; qsort(node2,8,sizeof(node2[0]),cmp_struct2); for(int i=0;i<8;i++) { cout<<node2[i].x<<" "<<node2[i].y<<"\t"; } cout<<endl; return 0; }
原文地址:http://blog.csdn.net/huolang_vip/article/details/42922223