折半查找
如下程序折半查找如何分别输出每一步的mid的值?求指教输入的每个字符中间要用空格间隔
#include<stdio.h>
#include<string.h>
void sort(char a[],int n)
{
int i,j;
char temp;
for( i=0;i < n-1;i++)
{
for( j=i+1;j<n;j++)
{
if(a[i] > a[j])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
}
int BinSearch(char a[],char ch,int n)
{
int low,high,mid;
low = 0;
high = n-1;
while(low <= high)
{
mid= low +(high-low)/2;
if(ch > a[mid])
low = mid+1;
else if(ch < a[mid])
high = mid-1;
else
return mid;
}
return -1;
}
int main()
{
char a[80];
char ch;
int k=0;
fgets(a,80,stdin);
scanf("%c",&ch);
// sort(a,80);
sort(a,strlen(a));
//puts(a);
k=BinSearch(a,ch,strlen(a));printf("\n");
if( k != -1)
printf("%d\n",k);
else
printf("0");
return 0;
}
我自己改成了这样
程序代码:
#include<stdio.h> #include<string.h> int BinSearch(char a[],char ch,int n) { int low,high,mid; low = 0; high = n-1; while(low <= high) { mid= low +(high-low)/2; if(ch > a[mid])//调试时显示这里有错,不知道怎么改 low = mid+1; else if(ch < a[mid]) high = mid-1; else return mid; printf("%d ",mid); } return -1; } int main() { char a[80]; char ch; int k=0,i,j; fgets(a,80,stdin); for(i=0;i<strlen(a);i++){ if(a[i]==' '){ a[i]=a[i+1]; }else{ j++; } } scanf("%c",&ch); k=BinSearch(a,ch,j); printf("\n"); if( k != -1) printf("%d\n",k); else printf("0"); return 0; }
[此贴子已经被作者于2016-12-19 10:18编辑过]