用折半法查找数据
题目是15个以排好序的数,新输入一个数,用折半法查找。我有两个问题:1、输入的数字在区间范围但是不是里面某一个数的时候,会陷入死循环,怎么样子让它输出“这个数不存在”?
2、最后输入Y/N时,为什么我不能输入。
#include <stdio.h>
#define N 15
main()
{
int s[N] = { 14,25,36,47,58,69,147,258,369,74,85,96,741,852,963}, i, j, temp, n;
int top, bottle, mid, sign;
char c;
for ( i = 1; i < N; i++ )
for ( j = 0; j < N - i; j++ )
if ( s[j] < s[j + 1] )
{
temp = s[j];
s[j] = s[j + 1];
s[j + 1] = temp;
}
for ( i = 0; i < N; i++ )
printf ("%d ",s[i]);
while ( 1 )
{
printf ("input a number:");
scanf ("%d",&n);
top = 1;
bottle = N;
sign = 1;
while ( sign == 1 )
{
mid = ( top + bottle ) / 2;
if ( n > s[0] || n < s[N - 1] )
{
printf ("the number is not exist");
sign = 0;
}
else
if ( n == s[mid] )
{
printf ("%d 's number is s[%d]\n",n,mid);
break;
}
else
if ( n > s[mid] )
bottle = mid - 1;
else
if ( n < s[mid] )
top = mid + 1;
}
printf ("continue? Y/N");
scanf ("%c",&c);
if ( c == 'n' || c == 'N' )
break;
}
}