#include <stdio.h>#include<stdlib.h>#include <math.h>#define MAX_SIZE 101#define SWAP(x,y,t) ((t)=(x),(x)=(y),(y)=(t))void sort (int [],int);int binsearch(int list[],int x,int left, int right);int compare(int x, int y);void main(void){ int i,n; int x,z; int list [MAX_SIZE]; printf("Enter the number of numbers to generate: "); scanf("%d",&n); if(n<1||n>MAX_SIZE) { fprintf(stderr,"Improper value of n\n"); exit(0); } for(i=0;i<n;i++) { list[i]=rand() % 1000; printf("%d ",list[i]); } sort(list,n); printf("\n sorted array:\n"); for(i=0;i<n;i++) printf("%d ",list[i]); printf("\n"); printf("please input the number you want search:"); scanf("%d",&x); z=binsearch(list,x,0,n-1); if(z=-1) printf("no such number"); else printf("\n %dis %dth number",x,z);}void sort(int list[],int n){ int i,j,min,temp; for(i=0;i<n-1;i++) { min=i; for(j=i+1;j<n;j++) if(list[j]<list[min]) min=j; SWAP(list[i],list[min],temp); }}
int binsearch(int list[],int x,int left,int right){
int middle=0; if (left<=right) { middle=(left+right)/2; switch(compare(x,list[middle])) { case -1: return binsearch(list,x,left,middle-1); case 0: return middle; case 1: return binsearch(list,x,middle+1,right); } } return -1;}
int compare(int x, int y){ if(x>y) return 1; if(x==y) return 0; if(x<y) return -1;}
int binsearch(int list[],int x,int left,int right){
int middle=0; if (left<=right) { middle=(left+right)/2; switch(compare(x,list[middle])) { case -1: return binsearch(list,x,left,middle-1); case 0: return middle; case 1: return binsearch(list,x,middle+1,right); } } return -1;}
int compare(int x, int y){ if(x>y) return 1; if(x==y) return 0; if(x<y) return -1;}