Quick sort
void qsort,(_PTR __base, size_t __nmemb, size_t __size, __compar_fn_t _compar);
- __base . พอร์ยเตอร์ของอาเรย์ตัวแรก
- __nmemb . จำนวนสมาชิกทั้งหมดที่ต้องการเรียงลำดับ
- __size . ขนาดของสมาชิกใน 1 หน่วย
- __compar_fn_t _compar . ฟังก์ชั่นการเทียบค่า
Binary search
void *bsearch,(const _PTR __key, const _PTR __base, size_t __nmemb, size_t __size, __compar_fn_t _compar);
- __key . คือที่อยู่(address) ของคียร์ที่ต้องการค้นหา
- นอกนั้นเหมือนกับ qsort
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#define MAX 10 | |
void display(int a[]); | |
int cmp(void *a,void *b); | |
int main(void) | |
{ | |
int a[MAX] = {8 ,9 ,7 ,1 ,5 ,4 ,3 , 0, 2, 6 }; | |
display(a); | |
qsort(a,MAX,sizeof(int),cmp); | |
display(a); | |
int key = 44; | |
int *searchResult; | |
searchResult = bsearch( &key,a,MAX,sizeof(int),cmp); | |
if( searchResult != NULL) | |
{ | |
printf("%d found ",*searchResult); | |
} | |
else | |
{ | |
printf("Not found %d",key); | |
} | |
return 0; | |
} | |
void display(int a[]) | |
{ | |
int i =0; | |
while(i<MAX) | |
{ | |
printf("%d ",a[i++]); | |
} | |
printf("\n"); | |
} | |
int cmp(void *a,void *b) | |
{ | |
// if ( *((int *)a) < *((int *)b)) return -1; | |
// if ( *((int *)a) == *((int *)b)) return 0; | |
// return 1; | |
return *((int *)a) - *((int *)b); | |
} |