C中的qsort函數__函數

來源:互聯網
上載者:User
一、簡介   原 型: void qsort(void *base, int nelem, int width, int (*fcmp)(const void *,const void *)); 功 能: 使用快速排序常式進行排序
 
參 數:1 待排序數組首地址 2 數組中待排序元素數量 3 各元素的佔用空間大小 4 指向函數的指標,用於確定排序的順序 說明:qsort函數是ANSI C標準中提供的,其聲明在stdlib.h檔案中,是根據二分法寫的,其時間複雜度為n*log(n)。      qsort要求提供的函數是需要自己定義的一個比較函數,比較函數使得qsort通用性更好。有了比較函數qsort可以實現對數組、字串、結構體等結構進行升序或降序排序。
     如int cmp(const void *a, const void *b)中有兩個元素作為參數,返回一個int值,如果比較函數返回大於0,qsort就認為a > b,返回小於0qsort就認為a < b。qsort知道元素的大小了,就可以把大的放前面去。如果你的比較函數返回本來應該是1的(即a > b),而卻返回-1(小於0的數),那麼qsort認為a < b,就把b放在前面去,但實際上是a > b的,所以就造成了降序排序的差別了。
     簡單來說,比較函數的作用就是給qsort指明元素的大小事怎麼比較的。   二、使用舉例(MinGW5測試通過)   1、對一維數組排序:        2、對字串排序:    
01 #include <stdio.h>
02 #include <stdlib.h>
03   
04 typedef char Element_type;
05   
06 Element_type list[] = "djfkwjefklwefagj"; 
07   
08 int Comp(const void *p1,const void *p2)
09 {
10     //降序排序
11     return strcmp((char *)p2,(char *)p1);
12     //升序排序
13     //return strcmp((char *)p1,(char *)p2);
14 }
15   
16 int main(void)
17 {
18     puts("排序前:");
19     puts(list);
20     printf("\n");
21       
22     //考慮還有字串結束符,這裡元素個數別忘減1
23     qsort(list, sizeof(list) / sizeof(Element_type) - 1, sizeof(Element_type), Comp);
24     system("pause");
25       
26     puts("排序後:");
27     puts(list);
28     printf("\n");
29       
30   
31     return 0;
32 }

3、按結構體中某個關鍵字排序(對結構體一級排序):  
01 #include <stdio.h>
02 #include <stdlib.h>
03   
04 struct Node
05 {
06     double data;
07     int other;
08 }s[100];
09   
10 int Comp(const void *p1,const void *p2)
11 {
12     return (*(Node *)p2)->data - (*(Node *)p1)->data;
13 }
14   
15 int main(void)
16 {
17     puts("排序前:");
18     //code
19     printf("\n");
20       
21     qsort(s, 100, sizeof(s[0]), Comp);
22     system("pause");
23       
24     puts("排序後:");
25     //code
26     printf("\n");
27   
28     return 0;
29 }
4、按結構體中多個關鍵字排序(對結構體多級排序)[以二級為例]:  
1 struct Node
2 {
3    int x;
4    int y;
5 }s[100];//按照x從小到大排序,當x相等時按y從大到小排序
 
1 int Comp(const void *p1,const void *p2)
2 {
3    struct Node *c = (Node *)p1;
4    struct Node *d = (Node *)p2;
5    
6   if(c->x != d->x) return c->x - d->x;
7    else return d->y - c->y;
8 }
5、對結構體中字串進行排序:  
01 struct Node
02 {
03     int data;
04     char str[100];
05 }s[100];
06   
07 //按照結構體中字串 str 的字典序排序
08 int Comp(const void *p1,const void *p2)
09 {
10     return strcmp((*(Node *)p1)->str,(*(Node *)p2)->str);
11 }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.