#include <stdio.h>
#define LENGTH 10000
void swap(int* a,int x,int y){
if (x == y) return;
a[x] ^= a[y];a[y] ^= a[x];a[x] ^= a[y];
}
void print(int* a,int x,int y){
int i;
for (i = x; i < y+1; i++)
printf("%d ",a[i]);
printf("\n");
}
int binarySearch(int* a,int l,int r,int k){
int mid;
while(l <= r){
mid = (l + r)/2;
if(a[mid] == k)
return mid;
else if(a[mid] > k)
r = mid - 1;
else
l = mid + 1;
}
return -1;
}
int main(){
int n = 10;
int a[LENGTH] = {1,3,5,5,8,13,15,16,23,31};
int k;
scanf("%d",&k);
printf("%d",binarySearch(a,0,n-1,k));
return 0;
}
二分查找(未通过poj验证)
最新推荐文章于 2020-09-12 21:39:40 发布