1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
| #define NUM 1000 int main() { int i = 0; int *abc = malloc(NUM*sizeof(int)); srand(0);
printf("\n====================随机生成 %d 个数==============================\n",NUM); for(i=0;i<NUM;i++) { abc[i] = rand()%(10*NUM); printf("%d ",abc[i]); } printf("\n"); printf("\n====================快速排序后结果==============================\n");
Qsort(abc,NUM); for(i=0;i<NUM;i++) { printf("%d ",abc[i]); } printf("\n"); printf("\n====================检查快速排序结果正确性========================\n");
for(i = 0;i<NUM-1;i++) { if(abc[i]>abc[i+1]) { printf("ERROR!!!,i=%d\n",i); break; } if(abc[i] == abc[i+1]) { printf("found a equal,i=%d,value %d\n",i,abc[i]); } } if(i == NUM-1) printf("good,sort is ok\n"); printf("\n==================二分查找某个数字是否存在===========================\n"); printf("\n"); int target = 123; int index = binary_search(abc, NUM, target, 0); printf("target %d, index is %d\n",target,index); if(index != -1) printf("abc[%d] = %d",index,abc[index]);
printf("\n==========对数组中每个数均二分查找一下,检查二分查找正确性==================\n");
for(i=0;i<NUM;i++) { target = abc[i]; index = binary_search(abc, NUM, target, 1); if(index == -1) { printf("ERROR,the value %d exist but you do not find out\n",target); break; } if(abc[index] != target) { printf("ERROR,you found a error index!,abc[%d] is not equals to %d\n",index,target); break; } } if(i == NUM) printf("binary_search check ok\n");
printf("\n==================特殊情况检查================================\n");
int tmp[] = {3,3,3,3,3,3,3,3,3,3,3}; target = 3; index = binary_search(tmp, sizeof(tmp)/sizeof(int), target, 1); printf("%d\n",index); index = binary_search(tmp, sizeof(tmp)/sizeof(int), target, 0); printf("%d\n",index); printf("\n======================over============================\n"); return 0; }
|