现在的位置: 首页 > Code > 正文
二分法查找的C语言实现
2014年12月06日 Code, 电脑相关 ⁄ 共 986字 评论数 1

看到一篇文章提到二分法排序,好久没写CODE。构思了一下。


#include
int binSearch(int, int, int);
main()
{
int i, n = 10, x = 7;
//这里如果把数组a[]定义为a[n],是错误的,不能定义变长数组。
int a[10];
printf("Please enter your num:/n");
//从标准输入给数组赋值的唯一方法:用for循环
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("The %d can be found in the arr, it is %dth of the arr/n",
x, binSearch(x,a,n));
}
/*第一种方法,判断都在循环内*/
int binSearch(int x, int a[], int n)
{
int low, high, mid;
low = 0;
high = n-1;
//注意,这里必须用<=, 用<不对,一直返回-1
while(low <= high)
{
mid = (low + high) / 2;
if(x < a[mid]) high = mid - 1; else if(x > a[mid])
low = mid + 1;
else
return mid;
}
return -1;
}


#include
int binSearch(int, int, int);
main()
{
int i, n = 10, x = 7;
//这里如果把数组a[]定义为a[n],是错误的,不能定义变长数组。
int a[10];
printf("Please enter your num:/n");
//从标准输入给数组赋值的唯一方法:用for循环
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("The %d can be found in the arr, it is %dth of the arr/n",
x, binSearch(x,a,n));
}
/*在循环内执行一次测试的方法*/
int binSearch(int x, int a[], int n)
{
int low, high, mid;
low = 0;
high = n-1;
mid = (low + high) / 2;
while((low <= high)&&(a[mid]!=x))
{
if(x < a[mid])
high = mid -1;
else
low = mid + 1;
mid = (low + high) / 2;
}
if(a[mid] == x)
return mid;
else
return -1;
}

建伟

目前有 1 条留言 其中:访客:0 条, 博主:0 条

  1. 美图共赏 : 2016年04月15日10:31:05  -49楼 @回复 回复

    美图在这里:http://www.fydzv.com/

给我留言

留言无头像?



×