#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;
}
快速排序
最新推荐文章于 2023-12-01 23:14:38 发布