题目:二分查找+快排(代码)
代码:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int one_sort(int arr[],int low,int high);
//快排
void quick_sort(int arr[],int low,int high)
{
if(low>=high)
return;
int mid=one_sort(arr,low,high);
quick_sort(arr,low,mid-1);
quick_sort(arr,mid+1,high);
}
int one_sort(int arr[],int low,int high)
{
int key=arr[low];
while(low<high)
{
while(low<high&&key<=arr[high])
high--;
arr[low]=arr[high];
while(low<high&&key>=arr[low])
low++;
arr[high]=arr[low];
}
arr[low]=key;
return low;
}
//二分查找
void search(int arr[],int low,int high,int key)
{
int mid=(low+high)/2;
if(low>high)
{ puts("查无此元素");
return;
}
if(key<arr[mid])
search(arr,low,mid-1,key);
else if(key>arr[mid])
search(arr,mid+1,high,key);
else
printf("下标为:%d\n",mid);
return;
}
int main(int argc, const char *argv[])
{
int arr[10]={5,6,8,1,2,3,4,7,9,10};
quick_sort(arr,0,9);
for(int i=0;i<10;i++)
{
printf("%d ",arr[i]);
}
puts("");
int num;
printf("请输入要查找的元素;\n");
scanf("%d",&num);
search(arr,0,9,num);
return 0;
}
结果: