快速排序

来源:互联网 发布:梦幻西游高级宝石算法 编辑:程序博客网 时间:2024/06/06 07:00

1、算法思想
 快速排序是C.R.A.Hoare于1962年提出的一种划分交换排序。它采用了一种分治的策略,通常称其为分治法(Divide-and-ConquerMethod)。

(1) 分治法的基本思想
 分治法的基本思想是:将原问题分解为若干个规模更小但结构与原问题相似的子问题。递归地解这些子问题,然后将这些子问题的解组合为原问题的解。

(2)快速排序的基本思想
 设当前待排序的无序区为R[low..high],利用分治法可将快速排序的基本思想描述为:
①分解:
 在R[low..high]中任选一个记录作为基准(Pivot),以此基准将当前无序区划分为左、右两个较小的子区间R[low..pivotpos-1)和R[pivotpos+1..high],并使左边子区间中所有记录的关键字均小于等于基准记录(不妨记为pivot)的关键字pivot.key,右边的子区间中所有记录的关键字均大于等于pivot.key,而基准记录pivot则位于正确的位置(pivotpos)上,它无须参加后续的排序。
注意:
 划分的关键是要求出基准记录所在的位置pivotpos。划分的结果可以简单地表示为(注意pivot=R[pivotpos]):
 R[low..pivotpos-1].keys≤R[pivotpos].key≤R[pivotpos+1..high].keys
其中low≤pivotpos≤high。
②求解:
  通过递归调用快速排序对左、右子区间R[low..pivotpos-1]和R[pivotpos+1..high]快速排序。
③组合:
 因为当”求解”步骤中的两个递归调用结束时,其左、右两个子区间已有序。对快速排序而言,”组合”步骤无须做什么,可看作是空操作。

#include <iostream>using namespace std;//交换元素void Swap(int* x, int* y) {    int t = *x;    *x = *y;    *y = t;}//调用Partition(a,low,high)时,对a[low..high]做划分,//并返回基准记录的位置int Partition(int a[], int low, int high) {    //以第一个元素作为基准值    //比pivot值小的元素放在数组的左边,比pivot值大的元素放在数组右边    int pivot = a[low];    //从区间两端交替向中间扫描,直至low=high为止    while (low < high) {        while (low < high && a[high] >= pivot)//pivot相当于在位置low上            high--;//从右向左扫描,查找第1个关键字小于pivot.key的记录a[high]        if (low < high)//表示找到的a[high]的关键字<pivot            Swap(&a[low++], &a[high]);//相当于交换a[low]和a[high],交换后low指针加1        while (low < high && a[low] <= pivot)//pivot相当于在位置high上            low++;//从左向右扫描,查找第1个关键字大于pivot.key的记录a[low]        if (low < high)//表示找到的a[low]的关键字>pivot            Swap(&a[low], &a[high--]);//相当于交换a[low]和a[high],交换后high指针减1    }    a[low] = pivot;    //基准记录已被最后定位    return low;}//对a[start..end]快速排序void QuickSort(int a[], int start, int end) {    if (start == end)        return;    //划分后的基准记录的位置,对a[start..end]做划分    int index = Partition(a, start, end);    if (index > start)        QuickSort(a,  start, index - 1);//对左区间递归排序    if (index < end)        QuickSort(a,  index + 1, end);//对右区间递归排序}void print(int a[], int length) {    for (int i = 0; i < length; i++)        cout << a[i] << " ";    cout << endl;}int main() {    int a[5] = { 3, 1, 2, 5, 4 };    QuickSort(a, 0, 4);    print(a,5)    return 0;}
0 0
原创粉丝点击