快排+折半查找

 1 #include<iostream>
 2 using namespace std;
 3 int quick_sort(int (&a)[1000],int low,int high){    //一趟快速排序,快排的核心!!!
 4     int key=a[low];
 5     a[0]=a[low]; //临时存放枢轴的元素值
 6     while(low<high){
 7         while(low<high&&a[high]>=key) high--;
 8         a[low]=a[high];
 9         while(low<high&&a[low]<=key) low++;
10         a[high]=a[low];
11     }
12     a[low]=a[0];
13     return low;   //返回枢轴的位置
14 }
15 void QuickSort(int (&a)[1000],int low,int high){   //快速排序
16     if(low<high){
17         int mid=quick_sort(a,low,high);   //一趟快排,获取枢轴的位置
18         QuickSort(a,low,mid);   //对在枢轴左边的数组进行递归排序
19         QuickSort(a,mid+1,high);    //对枢轴右边的数组进行递归排序
20     }
21 }
22 int Binary_search(int * a,int low,int high,int value){ //折半查找算法
23     if(low>high){
24         return -1; //说明没有找到元素,返回-1
25     }
26     int mid=(low+high)/2;
27     if(a[mid]==value){
28         return mid; //说明查找到了元素所在下标并且返回
29     }else if(a[mid]<value){
30         return Binary_search(a,mid+1,high,value);  //递归折半查找
31     }else{
32         return Binary_search(a,low,mid-1,value);   //递归折半查找
33     }
34 }
35 int main(){
36     int n,a[1000];
37     cin>>n;
38     for(int i=1;i<=n;i++){
39         cin>>a[i];
40     }
41     QuickSort(a,1,n);
42     cout<<"按从小到大快速排序后的序列为: "<<endl;
43     for(int i=1;i<=n;i++){
44         cout<<a[i]<<" ";
45     }
46     cout<<endl;
47     int value; //需要查找的值value
48     while(cin>>value){  //输入value,能够多次查询,ctrl+z 结束输入
49         int ans=Binary_search(a,1,n,value); //进行折半查找算法
50         if(ans==-1) cout<<"未查找到值 "<<value<<endl;  //下标返回-1说明数组里面无当前元素
51         else cout<<value<<"的所在数组下标为: "<<ans<<endl; //否则,返回所查找元素的数组下标
52     }
53     return 0;
54 }

快排的核心思想就是枢轴左边要么都是比它值大的,要么就是都是值比它小的,右边同理。

快排最优的时间复杂度为O(n*logn),最坏情况为要么全是逆序或者正序,时间复杂度为O(n*n),根据推导,平均时间复杂度为O(n*logn)。

就空间复杂度来说,主要是递归造成的栈空间的使用,最好情况,递归树的深度为log2n,其空间复杂度也就为O(logn),最坏情况,需要进行n‐1递归调用,其空间复杂度为O(n),平均情况,空间复杂度也为O(logn)。

折半查找就是二分

猜你喜欢

转载自www.cnblogs.com/ISGuXing/p/9118792.html
今日推荐