使用二分法查找数据,要c语言的源代码
发布网友
发布时间:2022-04-26 19:38
我来回答
共2个回答
热心网友
时间:2022-04-24 00:43
#include <stdio.h>
#include <stdlib.h>
#define MAX 5
static void sort(int val[], int n)
{
int temp, i, j;
for (i = 0; i < n; i++)
{
for (j = i+1; j < n; j++)
{
if (val[j]<val[i])
{
temp = val[j];
val[j] = val[i];
val[i] = temp;
}
}
}
}
static int bisearch(int number[], int n, int find) {
int low, mid, upper;
low = 0;
upper = n - 1;
printf("Search %d:", find);
while(low <= upper) {
mid = (low+upper) / 2;
if(number[mid] < find)
low = mid+1;
else if(number[mid] > find)
upper = mid - 1;
else
return mid;
}
return -1;
}
static void echo_result(int n)
{
if(n == -1)
{
printf("no found\n");
}
else
{
printf("found\n", n+1);
}
return;
}
int main()
{
int a[5] = {4,7,9,6,3};
int i;
int ret;
printf("array:");
for(i=0;i<5;i++)
{
printf("%d ",a[i]);
}
printf("\n");
sort(a, MAX);
/*For test*/
ret = bisearch(a, MAX, 6);
echo_result(ret);
ret = bisearch(a, MAX, 5);
echo_result(ret);
return 0;
}
热心网友
时间:2022-04-24 02:01
已写好,采纳后立即发送邮箱。