3C科技 娛樂遊戲 美食旅遊 時尚美妝 親子育兒 生活休閒 金融理財 健康運動 寰宇綜合

Zi 字媒體

2017-07-25T20:27:27+00:00
加入好友
C/C++ 內建 快速排序 [stdlib.h bsearch()] 函示庫 資料來源:https://winage.pixnet.net/blog/post/188269445 https://www.runoob.com/cprogramming/c-function-qsort.html 線上編譯: https://www.tutorialspoint.com/compile_c_online.php 程式01. #include #include int values[] = { 88, 56, 100, 2, 25 }; int cmpfunc (const void * a, const void * b) { return ( *(int*)a - *(int*)b ); } int main() { int n; printf("排序之前的列表:\n"); for( n = 0 ; n < 5; n++ ) { printf("%d ", values[n]); } qsort(values, 5, sizeof(int), cmpfunc); printf("\n排序之后的列表:\n"); for( n = 0 ; n < 5; n++ ) { printf("%d ", values[n]); } return(0); } 程式02.[各種資料類型程式片段] 一、對int類型數組排序 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類型) char word[100]; Sample: int cmp( const void *a , const void *b ) { return *(char *)a - *(int *)b; } qsort(word,100,sizeof(word[0]),cmp); 三、對double類型數組排序(特別要注意) 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); 四、對結構體一級排序 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); 五、對結構體二級排序 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); 六、對結構字符串進行排序 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); 七、對字符串進行排序 呼叫 qsort( (void*) array , Num , sizeof( char* ) , compareString ); 定義 int compareString(const void *a, const void *b) { return strcmp(*(char **)a, *(char **)b); } //char**)表示後面是一個指向char*資料形態的指標, 而char*在C裡多半當做字串使用, 因此你可以想成是String*, 也就是:*((String*)p1) 從一個指向字串的指標裡, 取出它所指向的字串. 最後不就是用strcmp比對兩個字串

本文由jashliaoeuwordpress提供 原文連結

寫了 5860316篇文章,獲得 23313次喜歡
精彩推薦