初学者:一个2分法查找数字的代码!不知道错在哪2分法代码哪一段直接跳过不执行!求大神帮忙!
#include<stdlib.h>#include<stdio.h>
#include<time.h>
void add(int a[], int n)
{
for (int i = 0; i < n - 1; i++)
{
int x = i;
for (int j = i + 1; j < n; j++)
{
if (a[x] > a[j])
{
x = j;
}
}
if (x != i)
{
a[x] = a[x] - a[i];
a[i] = a[x] + a[i];
a[x] = a[i] - a[x];
}
}
}
void sjs(int a[], int n)
{
int t = (int)time(NULL);
srand(t);
for (int i = 0; i < n; i++)
{
a[i] = rand()%1000;
/* printf("%d\n", a[i]);*/
}
}
int erfen(int a[], int n, int b)
{
for (int tou = 0, wei = n - 1, zhong = (n - 1) / 2; tou >= wei; zhong = (tou + wei) / 2)
{
if (a[zhong] == b)
return zhong;
else if (a[zhong] < b)
tou = zhong + 1;
else if (a[zhong] > b)
wei = zhong - 1;
}
return -1;
}
void main()
{
int a[1000];
int b;
sjs(a, 1000);
add(a, 1000);
for (int i = 0; i < 1000; i++)
{
printf("a[%d]=%d\n", i, a[i]);
}
scanf("%d", &b);
if (a[erfen(a, 1000, b)] == b)
{
printf("已经找到该数");
}
else
{
printf("没有查找到该数请重新输入");
}
system("pause");
}