zoukankan      html  css  js  c++  java
  • 哎呀 走马观花来到快排了

    排序算法之前都实现过,就当练练手吧。不过见识了快排的尾递归写法-=-

    #include<iostream>
    #include<algorithm>
    #include<memory>//the hearder file of shared_ptr
    #include <vector>
    #include <list>
    #include <map>
    #include <string>
    
    using namespace std;
    
    int partition(int* A, int low, int high) {
        int mid = (low + high) / 2;
        int key = A[mid];
        A[mid] = A[low];
        int last = low;
    
        for (int i = low + 1;i < high;i++) {
            if (A[i] < key)swap(A[++last], A[i]);
        }
        A[low] = A[last];
        A[last] = key;
    
        return last;
    }
    
    int h_partition(int *A, int low, int high) {
        //hoare-partition
        int i = low, j = high - 1;
        int key = A[low];
    
        while (true) {//分析循环实际上key值一直在被交换,若元素不互异则无法正常工作
        while (i<high&&A[i] < key)i++;
        while (j>=low&&A[j] > key)j--;
        if (i >= j)break;
        swap(A[i], A[j]);
        }
        return j;
    }
    
    void tail_qsort(int *A, int low, int high) {//尾递归版本
        if (high - low <= 1)return;//只剩一个元素
    
        while (low <= high) {
            int j = partition(A, low, high);
            tail_qsort(A, low, j);
            low = j + 1;
        }
    }
    
    void q_sort(int *A, int low, int high) {
        if (high - low <= 1)return;
    
        int j = h_partition(A, low, high);
        q_sort(A, low, j);
        q_sort(A, j + 1, high);
    }
    
    int main(void) {
        
        int a[15] = { 2,0,1,90,3,5,6,9,8,4,99,36,89,26,25 };
        tail_qsort(a, 0, 15);
        for (const int& mem : a)cout << mem << " ";
    
        cout << endl;
        return 0;
    }
  • 相关阅读:
    base64和Blob的相互转换
    限制文件上传的大小和尺寸
    git将本地项目提交到github
    vue-cli3创建项目时报错
    运行项目是node-sass报错的解决方法
    classList的使用
    将数组扁平化并去除其中重复数据,最终得到一个升序且不重复的数组
    移动端的图片放大
    js获取url中的参数
    HTML5-canvas
  • 原文地址:https://www.cnblogs.com/schsb/p/8569141.html
Copyright © 2011-2022 走看看