折半查找在C_free中运行不出来 求救
本帖最后由 番茄 于 2012-11-14 23:38 编辑# include <stdio.h>
int bin_search(int key[], int n, int k)
{
int low = 0, high = n - 1, mid;
while (low <= high)
mid = (low + high)/2;
{
if (key = k)
{
return mid;
}
else if (k > key)
{
low = mid + 1;
}
else
{
high = mid - 1;
}
}
return -1;
}
int main(void)
{
int a={11, 22, 33 ,55 , 66, 99, 42, 16, 98, 72};
printf ("the contents of the Arrsy a are \n");
int i;
int c;
for (i = 0; i < 10; i++)
printf ("%d ",a);
int k;
printf ("\n请输入要查询的数字");
scanf ("%d", &k);
c = bin_search(a, 10, k);
if (-1 != c)
{
printf ("%d", c);
}
else
{
printf ("chazhaoshibai");
}
return 0;
}
折半查找必须是有序的 mid = .. 应该在while循环里面 wangyexin 发表于 2012-11-14 08:48 static/image/common/back.gif
mid = .. 应该在while循环里面
嗯 是了呵呵 已经解决了谢谢 wangyexin 发表于 2012-11-14 08:46 static/image/common/back.gif
折半查找必须是有序的
呵呵粗心了嘿嘿 wangyexin 发表于 2012-11-14 08:46 static/image/common/back.gif
折半查找必须是有序的
嗯呵呵 呵呵,不错啊 不错啊,呵呵 代码有问题
#include<stdio.h>
void binsearch(int k,int a[],int n)
{
int mid,low,high,count = 0,count1 = 0;
low = 0;
high = n-1;
while(low <= high) //一定要是小于等于 次奥 啊 麻痹的老子调试了一晚上
{
count++;
mid = (low+high)/2;
if(k < a)
{
high = mid-1;
}
else if(k > a)
{
low = mid+1;
}
else if(k == a)
{
printf("查找成功!%d是序列的第%d个数\n",k,mid+1);
count1++;
break;
}
}
if(count1 == 0)
{
printf("查找失败,不存在这个数!");
}
}
void main()
{
int i,j,k;
int a;
printf("请输入序列长度:");
scanf("%d",&k);
printf("\n");
printf("请有序输入一个序列:");
for(i = 0;i < k;i++)
{
scanf("%d",&a);
}
printf("\n");
printf("请输入要查找的数:");
scanf("%d",&j);
binsearch(j,a,k);
} 我只是路过打酱油的。 路过打酱油的 学习了啊,呵呵 {11, 22, 33 ,55 , 66, 99, 42, 16, 98, 72};
这组数一看就不行,必须有规律,降序||升序 {:1_1:}厉害{:1_1:}厉害{:1_1:}厉害
页:
[1]