快速排序-C++代码

#include <iostream>

int partition(int a[], int l, int r)
{
    int i = l;
    int j = r + 1;
    int v = a[l];
    
    while (true) {
        while (a[--j] > v);
        while (i < j && a[++i] < v);
        
        if (i == j)
        {
            break;
        }
        std::swap(a[i], a[j]);
    }
    
    std::swap(a[i], a[l]);
    
    return i;
}

void quick_sort(int a[], int l, int r)
{
    if (l < r) {
        int m = partition(a, l, r);
        quick_sort(a, l, m - 1);
        quick_sort(a, m + 1, r);
    }
}

int main(int argc, const char * argv[])
{
    int a[] = {1, 1, 6, 6, 8, 3, 5, 100, 300, 200, 99, 99};
    quick_sort(a, 0, sizeof(a)/sizeof(a[0]) - 1);
    
    for (int i : a) {
        std::cout << i << ' ';
    }
    std::cout << std::endl;
    
    return 0;
}
    原文作者:CharlesZhangCh
    原文地址: https://www.jianshu.com/p/e06aad8496a6
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞