快速排序

#include<iostream>
#include<algorithm>
using namespace std;

void swap(int &a, int &b) {
    a = a ^ b;
    b = a ^ b;
    a = a ^ b;
}

// Must make sure pivotIndex belongs to [head, tail]
int partion(int a[], int head, int tail, int pivotIndex) {
    if (pivotIndex < head || pivotIndex > tail)
        exit(1);
    // First exchange the pivot with the first element
    if (pivotIndex != head) 
        swap(a[head], a[pivotIndex]);
    int pivot = a[head];
    while (head < tail) {
        while (head < tail && a[tail] >= pivot)
            tail--;
        swap(a[head], a[tail]);
        while (head < tail && a[head] < pivot) 
            head++;
        swap(a[head], a[tail]);
    }
    // put the pivot to the index
    a[head] = pivot;
    return head;
}

void quickSort(int a[], int start, int end) {
    if (start >= end)
        return;
    int pivotIndex = partion(a, start, end, start);
    quickSort(a, start, pivotIndex - 1);
    quickSort(a, pivotIndex + 1, end);
}

int main() {
    int a[] = {10, 9, 11, 15, 7, 2, 8, 17};
    for (int i = 0; i < 8; ++i) 
        cout << a[i] << " ";
    cout << endl;
    // In order to make quickSort have a nlgn performance, it may be need
    // to be sorted random first
    // random_shuffle(a, a+8);
    quickSort(a, 0, 7);
    for (int i = 0; i < 8; ++i) 
        cout << a[i] << " ";
    cout << endl;
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值