数组中的基本操作:顺序查找元素
#include <stdio.h> #define SIZE 10 int main( ) { int d[SIZE]={34, 43, 98, 72, 12, 47, 31, 43, 1, 78}; int i,key,index=-1; printf("Input a key you want to search: "); scanf("%d" , &key); for(i=0; i<SIZE; i++) if(key == d[i]) { index = i; break; } if(index >= 0) printf("The index of the key is %d .\n", index); else printf("Not found.\n"); return 0; }
用二分方法查找有序数组:一次比较, 缩减一半的规模
#include <stdio.h> #define SIZE 10 int main( ) { int d[SIZE] = {1, 3, 9, 12, 32, 41, 45, 62, 75, 77}; int low, high,mid,key,index=-1; printf("Input a key you want to search: "); scanf("%d" , &key); low=0,high=SIZE-1; while(low<=high) { mid=(low+high)/2; if(d[mid]==key){ index=mid; break; } else if(d[mid]>key) high=mid-1; else low=mid+1; } if(index >= 0) printf("The index of the key is %d .\n", index); else printf("Not found.\n"); return 0; }