C语言中怎么用折半查找法查找字符

C语言中怎么用折半查找法查找字符

前提是有序 序列。

排序是比较的字符的ascii码

先排序在查找

#include<stdio.h>

#include<stdlib.h>

#include<string.h>

#define n 10

void bubble(char str[])

{

int i,j;

char t;

for(i=0;i<strlen(str)-1;i++)

{

for(j=0;j<strlen(str)-i-1;j++)

if(str[j]>str[j+1])

{

t=str[j];

str[j]=str[j+1];

str[j+1]=t;

}

}

}

void select(char str[],char c)

{

int l=0,h=strlen(str),i;

while(l<=h)

{

i=(l+h)/2;

if(str[i]==c)

{

printf("the character is the %dth in the array.",i+1);

return;

}

else if (str[i]>c)h=i-1;

else l=i+1;

}

printf("the character cannot be found.");

}

int main(void)

{

int i;

char str[]="streetsovc";

char c="r"; //要查找对象

printf("%d",strlen(str));

bubble(str);

printf("拍序后\n");

printf("%s\n",str);

select(str,c);

system("pause");

return(0);

}

精选文章

相关文章

粤ICP备17098710号 微点阅读