• 三路快排板子


    还是觉得别人的快排写得太丑了

    双路快排

    void qsort2(int L, int R) {
        if(L >= R) {
            return ;
        }
    /*    //随机取值
        int index = rand() % (R - L + 1) + L;
        swap(nums[L], nums[index]);*/
        int key = nums[L];
        int i = L, j = R;
        while(i < j) {
            while(i < j && nums[j] >= key) {
                j--;
            }
            nums[i] = nums[j];
            while(i < j && nums[i] <= key) {
                i++;
            }
            nums[j] = nums[i];
        }
        nums[i] = key;
        qsort2(L, i - 1);
        qsort2(i + 1, R);
    }
    

    三路快排

    图示

    按i走,小于key的丢到前面去,大于的丢到后面去

    void qsort3(int *nums, int L, int R) {
        if(L >= R) {
            return ;
        }
        int index = rand() % (R - L + 1) + L;//随机种子
        swap(nums[index], nums[L]);
        int key = nums[L];
        int lt = L, i = L + 1, j = R;
        while(i <= j) {
            if(nums[i] < key) {
                swap(nums[i++], nums[lt++]);
            } else if(nums[i] > key){
                swap(nums[i], nums[j--]);
            }
            while(i <= j && nums[i] == key) {
                i++;//while一定要在if后,否则当所有数相同时,i越界后还会进入if判断
            }
        }
        qsort3(nums, L, lt - 1);
        qsort3(nums, j + 1, R);
    }
    
    int main() {
        int n, l, r;
        while(cin >> n >> l >> r) {
     /*       多组输入
            输入三个数,数组长度 n,取值范围 [l, r]*/
            int nums[n];
            for(int i = 0;i < n;++i) {
                nums[i] = rand() % (r - l + 1) + l;
            }
            cout << " !! " << endl;
            for(int i = 0;i < n;++i) {
                cout << nums[i] << " ";
            }
            cout << endl;
            qsort3(nums, 0, n - 1);
            for(int i = 0;i < n;++i) {
                cout << nums[i] << " ";
            }
            cout << " // " << endl;
        }
        return 0;
    }
    
  • 相关阅读:
    用户行为分析
    数据挖掘
    酒店舆情分析
    特征工程·TFIDF提取特征
    mongo.conf 配置信息
    Phpstudy(小皮面板) nginx 解析漏洞
    mvnw 是什么
    java8 函数式接口Function和BiFunction
    ArrayList去除重复元素 利用 HashSet
    idea svn提交 忽略.imi 以及.idea文件夹
  • 原文地址:https://www.cnblogs.com/shuizhidao/p/13719136.html
Copyright © 2020-2023  润新知