#include<stdio.h>
#include<string.h>
#include<conio.h>
void Bubble(char *item,int n);
int Seqsearch(char *item,int n,char key);
int Bsearch(char *item,int n,char key);
void main()
{
char s[256];
char Choice;
char key;
int iRet;
while(1)
{
printf("****************************************************\n");
printf("** 查找算法 **\n");
printf("** 1.顺序查找 2.二分查找 **\n");
printf("** 请你选择1-2功能操作,0--退出 **\n");
printf("****************************************************\n");
Choice=getche();
if(Choice=='0')
break;
else if(Choice=='1'||Choice=='2')
{
printf("\n\n请你输入你要查找的字符串:(<255个字符):\n ");
gets(s);
printf("\n请输入你要查找的字符:\n ");
key=getche();
printf("\n");
switch(Choice)
{
case '1':
iRet=Seqsearch(s,strlen(s),key);
break;
case '2':
Bubble(s,strlen(s));
printf("排序后的字符串为: %s\n",s);
iRet=Bsearch(s,strlen(s),key);
break;
default:
printf("请你输入“1-2”作为命令,谢谢!\n");
break;
}
if(iRet>=0)
printf(" 查找的字符%c位于是字符串的第%d位置\n",key,iRet+1);
else
printf(" 字符串中没有该字符%c!\n",key);
}
}}
int Seqsearch(char *item,int n,char key)
{
int i;
for(i=0;i<n;i++)
{
if(key==item[i])
return i;
}
return -1;
}
int Bsearch(char *item,int n,char key)
{int low=0,high=n-1,mid;
while(low<=high)
{
mid=(low+high)/2;
//printf("low=%d,mid=%d,high=%d\n",low,mid,high);
if(key<item[mid])
high=mid-1;
else if(key>item[mid])
low=mid+1;
else
return mid;
}
return -1;
}
void Bubble(char *item,int n)
{
int i,j;
char t;
for(i=1;i<n;i++)
{
for(j=n-1;j>=i;j--)
{
if(item[j-1]>item[j])
{
t=item[j-1];
item[j-1]=item[j];
item[j]=t;
}
}
}
return;
}
#include<string.h>
#include<conio.h>
void Bubble(char *item,int n);
int Seqsearch(char *item,int n,char key);
int Bsearch(char *item,int n,char key);
void main()
{
char s[256];
char Choice;
char key;
int iRet;
while(1)
{
printf("****************************************************\n");
printf("** 查找算法 **\n");
printf("** 1.顺序查找 2.二分查找 **\n");
printf("** 请你选择1-2功能操作,0--退出 **\n");
printf("****************************************************\n");
Choice=getche();
if(Choice=='0')
break;
else if(Choice=='1'||Choice=='2')
{
printf("\n\n请你输入你要查找的字符串:(<255个字符):\n ");
gets(s);
printf("\n请输入你要查找的字符:\n ");
key=getche();
printf("\n");
switch(Choice)
{
case '1':
iRet=Seqsearch(s,strlen(s),key);
break;
case '2':
Bubble(s,strlen(s));
printf("排序后的字符串为: %s\n",s);
iRet=Bsearch(s,strlen(s),key);
break;
default:
printf("请你输入“1-2”作为命令,谢谢!\n");
break;
}
if(iRet>=0)
printf(" 查找的字符%c位于是字符串的第%d位置\n",key,iRet+1);
else
printf(" 字符串中没有该字符%c!\n",key);
}
}}
int Seqsearch(char *item,int n,char key)
{
int i;
for(i=0;i<n;i++)
{
if(key==item[i])
return i;
}
return -1;
}
int Bsearch(char *item,int n,char key)
{int low=0,high=n-1,mid;
while(low<=high)
{
mid=(low+high)/2;
//printf("low=%d,mid=%d,high=%d\n",low,mid,high);
if(key<item[mid])
high=mid-1;
else if(key>item[mid])
low=mid+1;
else
return mid;
}
return -1;
}
void Bubble(char *item,int n)
{
int i,j;
char t;
for(i=1;i<n;i++)
{
for(j=n-1;j>=i;j--)
{
if(item[j-1]>item[j])
{
t=item[j-1];
item[j-1]=item[j];
item[j]=t;
}
}
}
return;
}