从键盘输入一个字符,用折半查找法找出该字符在已排序的字符串a中的位置。
#include<stdio.h>#include<string.h>
void sort(char a[],int n)
{
int i,j;
for( i=0;i < strlen(a)-1;i++)
{
for( j=i+1;j<strlen(a);j++)
{
if(a[i] < a[j])
{
char temp;
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;
fgets(a,80,stdin);
scanf("%c",&ch);
sort(a,80);
k=BinSearch(a,ch,strlen(a));
if( k != -1)
printf("该字符在字符串中的第%d位.\n",k);
else
printf("The char is not in the string.\n");
return 0;
}