Presentation is loading. Please wait.

Presentation is loading. Please wait.

C qsort.

Similar presentations


Presentation on theme: "C qsort."— Presentation transcript:

1 C qsort

2 C qsort 原形 void qsort(void* base, size_t n, size_t size int (*cmp) (const void*, const void*) ) 用法 # include string.h 功能 快速排序

3 C qsort 說明 陣列基礎的快速排序法函數,陣列是參數 base,n 是陣列大小,size 是每個元素的大小,最後的參數是指向函數的指標,這是比較元素大小的函數。

4 1. 對int類型數組排序 int num[100]; int cmp ( const void *a , const void *b )
{ return *(int *)a - *(int *)b; } qsort(num, 100, sizeof(num[0]), cmp);

5 2.對char類型數組排序 char word[100]; Sample: int cmp( const void *a , const void *b ) { return *(char *)a - *(int *)b; } qsort(word,100,sizeof(word[0]),cmp);

6 3.對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);

7 4.對struct結構體一級排序 struct In { double data; int other; } s[100] int cmp( const void *a ,const void *b) { return ((struct In *)a)->data>((struct In *)b)->data ? 1 : -1; } qsort(s,100,sizeof(s[0]),cmp);

8 5.對struct結構體二級排序 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);

9 6.對結構字符串進行排序 struct In {int data;char str[100];} s[100]; //按照結構體中字符串str的字典順序排序 int cmp ( const void *a , const void *b ) { return strcmp( ((struct In *)a)->str, ((struct In *)b)->str); } qsort(s,100,sizeof(s[0]),cmp);

10 7.對字符串進行排序 呼叫 qsort( (void*) array, Num, sizeof(char *), compareString ); 定義 int compareString(const void *a, const void *b) { return strcmp(*(char **)a, *(char **)b); }

11 7.對字符串進行排序 像以下這種就可以用上面的compare函式來處理 array[0] = " " array[1] = " " #include <stdio.h> #include <string.h> #include <stdlib.h> int cmpr(const void *a, const void *b); char s[1000]; char *s_pointer[1000]; int i=0,j=0;

12 7.對字符串進行排序 int main() { while((fgets(s,1000,stdin))!=NULL) if(i<10) s_pointer[i++]=strdup(s); else break; qsort(s_pointer, i, sizeof(char *), cmpr); while(j<i) printf("%s\n",s_pointer[j++]); system("pause"); return 0; }

13 7.對字符串進行排序 int cmpr(const void *a, const void *b) { return strcmp(*(char**)a,*(char**)b); }

14 Reference


Download ppt "C qsort."

Similar presentations


Ads by Google