6-1 3.3 BinarySearch (15分)
题目:Write a function to implement the binary search algorithm:
decide if a particular value x occurs in the sorted array v
the elements of v must be in increasing order
the function returns the position/index (a number between 0 and n-1) if x occurs in v, and -1 if not.
#include <stdio.h>
int binsearch(int x, int v[], int n);
int compare (const void * a, const void * b);
int main ()
{
int n; // size of array v
int m; // number of calling search
scanf("%d", &n);
int * v = (int*)malloc(sizeof(int) * n);
for(int i = 0; i < n; i++) {
scanf("%d", &v[i]);
}
qsort(v, n, sizeof(int), compare); // to sort array v by calling standard library function
scanf("%d", &m);
while(m--) {
int x;
scanf("%d", &x);
printf("%d\n", binsearch(x, v, n));
}
free(v);
return 0;
}
int compare (const void * a, const void * b)
{
return ( *(int*)a - *(int*)b );
}
/* Your function(s) will be put here */
答案:
int binsearch(int x, int v[], int n){
if(n<100){
for(int i=0;i<n;i++){
if(v[i]==x) return i;
}
return -1;
}
//上面是小数据,下面的是大数据
int low,high,mid,count=0,count1=0;
low=0;
high=n-1;
while(low<high) //査找范围不为0时执行循环体语句
{
mid=(low+high)/2; //求中间位置
if(x<v[mid]) //x小于中间值时
high=mid-1; //确定左子表范围
else if(x>v[mid]) //x 大于中间值时
low=mid+1; //确定右子表范围
else if(x==v[mid]) //当x等于中间值时,证明查找成功
{
return mid;
}
}
return -1;
}
修修补补写出来的,有简单方法大佬可联系我改善。