C語言標準函式 qsort bsearch

2021-07-29 22:29:05 字數 2100 閱讀 1187

#include#include#include#include#define size 1000000

int compare_int (const void *a, const void *b)

int compare_char (const void *a, const void *b)

int arr_int[size];

char arr_char[size][5] = ;

typedef struct nodenode;

int compare_iarr (const void *a, const void *b)

int main ()

}/* for(i = 0; i < n; i ++)

printf("\n");

}*/qsort(a, n, sizeof(a[0]), compare_iarr);

/* printf("\n");

for(i = 0; i < n; i ++)

printf("\n");

}*/node nod = ;

if((node *)bsearch(&nod, a, n, sizeof(a[0]), compare_iarr) != null)

printf("yes");

int t1, t2;

int ci = 0;

t1 = clock();

while(ci < 100000)t2 = clock();

printf("--%d--", t2 - t1);//對於 迴圈次數多且排序搜尋集合大的仍然很慢,必須用記憶搜尋 記憶體換時間

//整形排序運用

printf("\n整形排序運用 \n");

n = 5;

for(i = 0; i < n; i ++)arr_int[3] = 41;

for(i = 0; i < n; i ++)printf("\n");

qsort(arr_int, n, sizeof(arr_int[0]), compare_int);

for(i = 0; i < n; i ++)printf("\n");

// bsearch() 二元搜尋

/* key指向所要查詢的元素,base指向進行查詢的陣列,nmem為查詢長度,

一般為陣列長度,size為每個元素所佔的位元組數,一般用sizeof(...)表示,

comp指向比較子函式,它定義比較的規則。需要注意的是,資料必須(注意是必須)是經過預先排序的(因為選擇compace後,它預設已經排序),

而排序的規則要和comp所指向比較子函式的規則相同。如果查詢成功則返回陣列中匹配元素的位址,

反之則返回空。對於有多於乙個的元素匹配成功的情況,bsearch()未定義返回哪乙個。

cur 返回陣列對於的 key指向所要查詢的元素的最後出現的位置

*/ int key = 91;

int *cur;

cur = (int *)bsearch(&key, arr_int, n, sizeof(int), compare_int);

if(cur == null) //key在陣列裡面則不為bull

printf("%d不在函式裡面\n", key);

else

printf("%d在函式裡面\n", key);

for(i = 0; i < n; i ++)

//字串排序運用

printf("字串排序運用 \n");

n = 5;

for(i = 0; i < n; i ++)printf("\n");

qsort(arr_char, n, sizeof(arr_char[0]), compare_char);

for(i = 0; i < n; i ++)printf("\n");

char *cu;

char str[5] = ;

cu = (char *)bsearch(str, arr_char, n, sizeof(str), compare_char);

if(cu != null)

printf("yes");

return 0;

}

C語言常用標準函式

atof str 字串 浮點型 atoi str 字串 整型 atol str 字串 長整型 itoa num,str,radix 整型 字元型 radix為使用者指定的進製數 ltoa num,str,radix 長整型 字元型 strlwr str 大寫 小寫 strupr str 小寫 大寫 ...

c語言 12 標準c庫函式

標準c庫函式 標準c庫函式,是由ansi組織定義的一系列標準函式,在各種平台,各個編譯器都支援。ansi 是 美國國家標準協會,於是linux和windows環境下編譯執行,結果一致 這個沒啥學的,會用就行,知道哪些庫可以實現哪些功能,多用幾次就記住了,最初認識的 stdio.h stdio 意思是...

理解C語言標準I O函式

通常在c 語言中使用標準i o 函式的第一步就是用fopen 開啟乙個檔案 標準輸入輸出是自己開啟的 fopen 函式在開啟乙個檔案的同時還建立了乙個緩衝區,還有乙個包含檔案和緩衝區相關資料的資料結構,我們熟知的file 指標型別,file 型別的指標並不是指向檔案本身,而是指向上面所說的包含檔案資...