#include <stdio.h>
#include <stdlib.h>
//二分法查找代码实现,其中嵌套快速排序!
void quickSort(int array[],int,int);
int oneSort(int array[],int,int);
void showArr(int array[],int len);
int binarySearch(int array[],int start,int end,int value);
int binarySearch2(int array[],int start,int end,int value);
int main()
{
int s;
int array[]= {23,14,-5,6,18,13,20,-6,43,7};
//quickSort(array,0,9);
//showArr(array,10);
printf(“请输入需要查找的数据:”);
scanf("%d",&s);
printf("%d",s);
int result=binarySearch(array,0,9,s);
printf("%d",result+1);
return 0;
}
void quickSort(int array[],int start,int end)
{
if(start>=end)
{
return ;
}
int index=oneSort(array,start,end);
quickSort(array,start,index-1);
quickSort(array,index+1,end);
}
int oneSort(int array[],int start,int end)
{
int i=start;
int j=end;
int base=array[i];
while(i<j){
while(i<j&&base<=array[j]){
j–;
}
if(i<j){
array[i]=array[j];
i++;
}
while(i<j&&base>=array[i]){
i++;
}
if(i<j){
array[j]=array[i];
}
}
array[i]=base;
return i;
}
void showArr(int array[],int len)
{
int i=0;
printf("\n");
for(; i<len; i++)
{
printf("%d\t",array[i]);
}
printf("\n");
}
int binarySearch(int array[],int start,int end,int value){
//先进行排序
quickSort(array,start,end);
showArr(array,10);
return binarySearch2(array,start,end,value);
}
int binarySearch2(int array[],int start,int end,int value){
if(start>end){
return -1;
}
int middle=(start+end)/2;
if(array[middle]==value){
return middle;
}else if(array[middle]>value){
return binarySearch2(array,start,middle-1,value);
}else{
return binarySearch2(array,middle+1,end,value);
}
}