#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!"); } }

评论