谁能教教我?用比较容易理解的方法做。。。
有个15数按由小到大顺序存放在一个数组中,输入一个数,要求用折半查找法找出该数组中第几个元素的值。如果该数不在数组中,输出‘未找到’
root@~ #cat 5.c #include <stdio.h> #include <time.h> int main (void) { srand((unsigned)time(NULL)); int i,j,a[15]={1,2,4,6,7,9,10,13,14,15,17,19,20,29,30}; j=rand()%30+1; int mid,low,high; low=0,high=14; printf ("Original array is: "); for(i=0;i<15;i++) { printf ("%i ",a[i]); } printf ("\nRandom element is :%i\n",j); while(low<=high) { mid=(low+high)/2; if(a[mid]==j) { printf ("Position No.%i\n",mid); return 0; } if(a[mid]<j) { low=mid+1; } if(a[mid]>j) { high=mid-1; } } printf ("No Found!\n"); return 0; } root@~ #
root@~ #./5 Original array is: 1 2 4 6 7 9 10 13 14 15 17 19 20 29 30 Random element is :11 No Found! root@~ #./5 Original array is: 1 2 4 6 7 9 10 13 14 15 17 19 20 29 30 Random element is :5 No Found! root@~ #./5 Original array is: 1 2 4 6 7 9 10 13 14 15 17 19 20 29 30 Random element is :20 Position No.12 root@~ #./5 Original array is: 1 2 4 6 7 9 10 13 14 15 17 19 20 29 30 Random element is :14 Position No.8 root@~ #./5 Original array is: 1 2 4 6 7 9 10 13 14 15 17 19 20 29 30 Random element is :8 No Found! root@~ #./5 Original array is: 1 2 4 6 7 9 10 13 14 15 17 19 20 29 30 Random element is :2 Position No.1 root@~ #