#include<stdio.h>
#include<stdlib.h>
#define N 10
typedef struct
{
int *elem;
int length;
}list;
list L;
int *head;
void initial_list()
{
L.length=N;
L.elem=NULL;
}
void create_list()
{
int i=0;
head=L.elem=(int *)malloc(N*sizeof(int));
if(!L.elem)
{
printf("overflow!");
exit(0);
}
printf("please input the sequential list(%d):\n",N);
while(i<N)
{
printf("\nthe %dth elem:",i+1);
scanf("%d",&(L.elem[ i ]));
i++;
}
getchar();
}
int issequential_list()
{
int i=0;
L.elem=head;
while(i<N-1)
{
if(L.elem[ i ]>L.elem[ i+1 ])
return 0;
i++;
}
return 1;
}
void search_key()
{
int key,i;
char ch;
while(1)
{
i=0;
printf("\nplease input the key:\n");
scanf("%d",&key);
getchar();
L.elem=head;
while(i<N)
{
if(L.elem[ i ]==key)
{
printf("find it at %dth elem.\n",i+1);
break;
}
i++;
}
if(i==N)
printf("not find!\n");
printf("Are you want to continue search?Y or N?:");
scanf("%c",&ch);
getchar();
if(ch=='N'||ch=='n')
break;
}
}
void devide_search_key(int start,int end,int e)
{
int n=(start+end)/2;
if(start==end)
{printf("\ncannot find !!");
return;
}
if(L.elem[ n ]==e)
{
printf("\nfind it at the %dth elem",n+1);
return;
}
else
{
if(L.elem[ n ]>e)
devide_search_key(start,n,e);
else
devide_search_key(n,end,e);
}
return;
}
main()
{
int choice,key,start,end;
char ch;
clrscr();
printf("1.sequential search.\n 2.devide search.\n3.quit.\n");
printf("please choose the search method:");
scanf("%d",&choice);
printf("\n");
switch(choice)
{
case 1:
initial_list();
create_list();
search_key();
break;
case 2:
initial_list();
create_list();
while(1)
{
if(issequential_list())
{
while(1)
{
start=0;
end=N-1;
printf("\n please input the key:");
scanf("%d",&key);
getchar();
devide_search_key(start,end,key);
printf("Are you want to continue search?Y or N?:");
scanf("%c",&ch);
getchar();
if(ch=='N'||ch=='n')
goto loop;
}
}
else
{
printf("\nwhat you input is not sequential list.");
printf("\nplease create it again!");
}
}
loop:
break;
case 3:
exit(0);
default:
printf("\nerror dut to the wrong input format!");
}
}
正文
顺序和二分查找2005-07-04 12:53:00
【评论】 【打印】 【字体:大 中 小】 本文链接:http://blog.pfan.cn/jay0518/2514.html
阅读(3703) | 评论(0)
版权声明:编程爱好者网站为此博客服务提供商,如本文牵涉到版权问题,编程爱好者网站不承担相关责任,如有版权问题请直接与本文作者联系解决。谢谢!
评论