二分查找出了个错
第一个元素和最后一个元素查找不到 求解[/color]程序代码:
#include <stdio.h> #include <stdlib.h> #include <time.h> void insertSort(int a[],int n) { int i,j; for(i=2;i<=n;i++) { a[0] = a[i]; j = i-1; while(a[0] < a[j]) { a[j+1] = a[j]; j--; } a[j+1] = a[0]; } } int binarySearch(int a[],int n,int key) { int mid,high,low; high = n; low = 1; while(low < high) { mid = (low+high)/2; if(key < a[mid]) high = mid - 1; else if(key > a[mid]) low = mid + 1; else if(a[mid] == key) return mid; } return -1; } int main() { int a[11],i,key; srand((unsigned long)time(0)); for(i = 1 ; i <= 10; i++) { a[i] = rand() % 100; } insertSort(a,10); for(i = 1 ; i <= 10 ; i++) { printf("%d ",a[i]); } printf("\nKEY : "); scanf("%d",&key); printf("The index of %d is %d\n",key,binarySearch(a,10,key)); return 0; }