• 快速排序C++


    #include<iostream>
    #include<cstdio>
    #include<cstring>
    #include<queue>
    #include<vector>
    #include<algorithm>
    using namespace std;
    const int si = 500;
    int arr[si];
    int n;
    void showarray(){
        for (int i = 1; i <= n; i++) {
            cout << arr[i] << " ";
        }
        cout << endl;
    }
    int partition(int a[], int l, int r) {
        showarray();
        int pivot = a[l];//这一个作为中心 也是暂存temp
        while (l < r) {//显然 每一次这个 while (l<r)只会交换两个元素
            while (l < r && a[r] >= pivot) r--;//退出循环时 a[r]比pivot小 应该在pivot左边 而在右边 把它倒腾到左边的位置 a[l] = a[r]; l这个位置刚刚好没人用
            a[l] = a[r];//把a[r]放在左边
            while (l < r && a[l] <= pivot) l++;//退出循环时 a[l]比pivot大 应该在pivot右边 而在左边 把它倒腾到右边的位置 a[r] = a[l]; r这个位置刚刚好没人用
            a[r] = a[l];//把a[l]放在右边
        }//两个子while循环多次之后 就能得到 左边都比pivot小 右边都比pivot大的序列
    
        a[l] = pivot;//还给他
        return l;//l就是pivot的位置
    }
    void Qsort(int a[], int l, int r) {
        if (l < r) {
            int pivot = partition(a, l, r);
            //pivot 中心 不用动
            Qsort(a, l, pivot - 1);
            Qsort(a, pivot + 1, r);
        }
    }
    int main(){
        cin >> n;
        for (int i = 1; i <= n; i++) {
            cin >> arr[i];
        }
        Qsort(arr, 1, n);
        //测试序列
        //10 1 9 2 8 4 7 6 0 3 5
        //20 5 1 2 34 70 1 40 4 13 4 1 9 2 8 4 7 6 0 3 5
        //8 65 57 45 39 12 98 86 35
        //showarray();
        return 0;
    }
    

      

  • 相关阅读:
    margin塌陷(collapse)
    this的值
    变量、函数声明提升
    Git与Svn的区别—笔记1
    ECMAScript 总结
    正则表达式
    i2c 通信
    player/stage 学习---安装
    各种分区类型对应的partition_Id
    ubuntu 映射网络驱动器到本地
  • 原文地址:https://www.cnblogs.com/smatrchen/p/13765919.html
Copyright © 2020-2023  润新知