• 排序算法之快速排序


    基本思想

      快速排序是冒泡排序的一种改进,其基本思想是通过一趟排序将数据分割大于基准值和小于基准值两部分,按照该方法对两部分数据进行快速排序,整个排序过程可以使用递归或者循环来实现。快速排序是通常被认为在同数量级(O(nlog2n))的排序方法中平均性能最好的。但若初始序列按关键码有序或基本有序时,快排序反而蜕化为冒泡排序。,另外快速排序不是稳定的排序算法。

    实现代码

    递归实现

    #include<iostream>
    using namespace std;
    
    void print(int a[], int n)
    {
        for (int j = 0; j<n; j++) {
            cout << a[j] << "  ";
        }
        cout << endl;
    }
    
    void swap(int *a, int *b)
    {
        int tmp = *a;
        *a = *b;
        *b = tmp;
    }
    
    int partition(int a[], int low, int high)
    {
        static int count = 1;
        int privotKey = a[low];//基准元素  
        while (low < high) 
        {    
        //从表的两端交替地向中间扫描 while (low < high && a[high] >= privotKey) --high; //从high 所指位置向前搜索,至多到low+1 位置。将比基准元素小的交换到低端 swap(&a[low], &a[high]); while (low < high && a[low] <= privotKey) ++low; swap(&a[low], &a[high]); } cout << ""<<count<<"次排序结果" << endl; print(a, 10); ++count; return low; }
    void quickSort(int a[], int low, int high) { if (low < high) { int privotLoc = partition(a, low, high); //将数据一分为二 quickSort(a, low, privotLoc - 1); //递归对低子表递归排序 quickSort(a, privotLoc + 1, high); //递归对高子表递归排序 } } int main() { int a[10] = { 3,1,5,7,2,4,9,6,10,8 }; cout << "初始值:";print(a, 10); quickSort(a, 0, 9); cout << "结果:"; print(a, 10); }
  • 相关阅读:
    自定义排序方式
    Ajax 调用(传值)一般处理程序(.ashx)
    把一个文件夹下的所有excel添加到datatable
    list比较交集
    禁用未登录通过连接下载文件
    加密方式
    使用response.write输出excel
    linux安装OpenCV以及windows安装numpy、cv2等python2.7模块
    哈希长度扩展攻击(Hash Length Extension Attack)利用工具hexpand安装使用方法
    yafu安装使用方法以及mismatched parens解决方法
  • 原文地址:https://www.cnblogs.com/chmm/p/7426624.html
Copyright © 2020-2023  润新知