C语言学习——二分法排序:
#include <stdio.h>
int main()
{ char a[10] = {1,2,3,4,5,6,7,8,9,10};
int low = 0,high = 9;
int mid,x;
printf("please input a number:\n");
scanf("%d",&x);
while(low <= high)
{
mid = (low + high) / 2;
if(x < a[mid])
{
high = mid - 1;
}
else
if(x > a[mid])
{
low = mid + 1;
}
else
if(x == a[low])
{
printf("a[%d]\n",low);
break;
}
if(x == a[high])
{
printf("a[%d]\n",high);
break;
}
if(x == a[mid])
{
printf("a[%d]\n",mid);
break;
}
}
if(low > high)
{
printf("NULL\n");
}
return 0;
}