周先森博客

快速排序详解

 

 

题目描述:对2,3,1,6,4,5进行按从小到大进行快速排序

解题:

分解对待排序列a[p:r](看成从p到r的一组序列)进行划分,以元素a[p]作为基准,将a[p:r]分成a[q:p-1],a[p],a[p+1:r]三个部分

子问题递归:递归求解根据基准分解出来的子问题a[q:p-1],a[p+1:r]

合并:递归返回的结果是已经排好序的结果

首先选择第一个数作为基准为2,从j开始,向前推进,寻找一个比2更小的

 找到1比2小,1,2进行交换

 

 然后i从前往后走,找比2大的数

 

找到3比2大,交换两数

 

继续进行j从当前位置往前找,直到i=j结束第一趟循环

第一趟循环之后,基准2就找到了它最终的位置,2左边的都是比2小的,2右边的都是比2大的数。

接下来进入第二趟循环,分别把2左边和2右边的都看成两个同样的子问题进行递归运算,后面的就是递归的过程

下面给出代码:

#include<iostream>
#include<algorithm>

using namespace std;
template<class type>
void quicksort(type a[],int p,int r)
{
if (p<r){
int q = partition(a,p,r);
quicksort(a,p,q-1);
quicksort(a, q + 1, r);
}
}


template <class type>
int partition(type a[],int p,int r)
{
int i = p, j = r + 1;
type x = a[p];
while (true){
while (a[++i] < x&&i < r);
while (a[--j]>x);
if (i>=j){
break;
}
swap(a[i],a[j]);
}
a[p] = a[j];
a[j] = x;
return j;
}

int main(){
int a[] = { 2, 3, 1, 7, 4, 5, 6 ,'\0'};
quicksort(a,0,7);
for (int i = 1; i <=7;i++)
cout << a[i]<<" ";
return 0;
}

 

posted on 2019-01-02 22:29  Mr_eclipse  阅读(657)  评论(0编辑  收藏  举报

导航