C庫函數qsort七種使用方法樣本

來源:互聯網
上載者:User
七種qsort排序方法<本文中排序都是採用的從小到大排序>一、對int類型數組排序C++代碼int num[100];  Sample:int cmp ( const void *a , const void *b )  {        return *(int *)a – *(int *)b;  }  qsort(num,100,sizeof(num[0]),cmp);  二、對char類型數組排序(同int類型)C++代碼char word[100];  Sample:int cmp( const void *a , const void *b )  {       return *(char *)a – *(char*)b;  }  qsort(word,100,sizeof(word[0]),cmp)  三、對double類型數組排序(特別要注意)C++代碼double in[100];  int cmp( const void *a , const void *b )  {       return *(double *)a > *(double *)b ? 1 : -1;  } qsort(in,100,sizeof(in[0]),cmp);  四、對結構體一級排序C++代碼struct In {  double data;  int other;  }s[100]  //按照data的值從小到大將結構體排序,關於結構體內的排序關鍵資料data的類型可以很多種,參考上面的例子寫  int cmp( const void *a ,const void *b)  {        return (*(In *)a).data > (*(In *)b).data ? 1 : -1;  }  qsort(s,100,sizeof(s[0]),cmp);  五、對結構體二級排序C++代碼struct In {      int x; int y;  }s[100];  //按照x從小到大排序,當x相等時按照y從大到小排序  int cmp( const void *a , const void *b )  {       struct In *c = (In *)a;       struct In *d = (In *)b;       if(c->x != d->x) return c->x – d->x;       else return d->y – c->y;  }  qsort(s,100,sizeof(s[0]),cmp);  六、對字串進行排序C++代碼struct In {      int data; char str[100];  }s[100];  //按照結構體中字串str的字典順序排序  int cmp ( const void *a , const void *b )  {       return strcmp( (*(In *)a)->str , (*(In *)b)->str );  }  qsort(s,100,sizeof(s[0]),cmp);  七、計算幾何中求凸包的cmpC++代碼int cmp(const void *a,const void *b)  //重點cmp函數,把除了1點外的所有點,旋轉角度排序  {       struct point *c=(point *)a;       struct point *d=(point *)b;       if( calc(*c,*d,p[1]) < 0) return 1;       else if( !calc(*c,*d,p[1])      && dis(c->x,c->y,p[1].x,p[1].y) < dis(d->x,d->y,p[1].x,p[1].y))      //如果在一條直線上,則把遠的放在前面      return 1; else return -1;  }  PS: 其中的qsort函數包含在的標頭檔裡,strcmp包含在的標頭檔裡

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.