• (9)交换排序之二 快速排序


          快速排序(Quick Sort)是对起泡排序的一种改进。它的基本思想是,通过一趟排序将待排序记录分割成独立的两部分,其中一部分记录的关键字均比另一部分记录的关键字小,则可分别对这两部分记录继续进行排序,以达到整个序列有序。

    // 快速排序
    void CExchangeSort::QuickSort(void)
    {
    const int count = 9, length = count -1;
    int L[count] = {0, 49, 38, 65, 97, 76, 13, 27, 49};
    int low = 1;
    int high = length;
    QuickSort(L, low, high);
    //打印排序结果。
    for (int i = 0; i <= length; ++ i)
    {
    cout
    << L[i] << "\t";
    }
    cout
    << endl;
    }


    // 快速排序之递归
    void CExchangeSort::QuickSort(int L[], int low , int high)
    {
    if (low < high)
    {
    int pivotloc = Partition(L, low, high); //拿到枢轴记录的位置
    QuickSort(L, low, pivotloc - 1);
    QuickSort(L, pivotloc
    + 1, high);
    }
    }


    // 快速排序之分区
    int CExchangeSort::Partition(int L[], int low , int high)
    {
    L[
    0] = L[low];
    int pivotkey = L[low];
    while(low < high)
    {
    while (low < high && L[high] >= pivotkey)
    -- high;
    L[low]
    = L[high];
    while (low < high && L[low] <= pivotkey)
    ++ low;
    L[high]
    = L[low];
    }
    L[low]
    = L[0];
    return low;
    }

          首先拿到枢轴位置,然后对低于枢轴位置的序列进行分区(也是排序的一个过程),再对高于枢轴位置的序列进行同样的操作。如上面的序列。第一次分区后序列中,元素[1]到[8]变成27, 38, 13, 49, 76, 97, 65, 49。4是枢轴位置。很明显元素[4]之前都是小于49的,[4]之后的关键值都是大于等于49的。同样对元素[1]...[4]和元素[5]...[8]这两段再分别进行Partition的过程。如此递归,直到low不小于high,说明连续两个元素都进行了比较。递归依次返回。

  • 相关阅读:
    AE开发中Geometry到Polyline/Polygon的转换--转载
    asp.net MVC Views-----Controller传递数据方法
    百度翻译APi接口实现
    javascript添加删除行信息
    XMLDocument
    GDI绘制图像
    测试局域网内网络数据
    HL7 V2 分隔符
    IHE-PIX 备注
    数据库关键字 (Oracle, SQL Server, DB2)
  • 原文地址:https://www.cnblogs.com/wanggary/p/2034111.html
Copyright © 2020-2023  润新知