快速排序的两个实现,测试用例不多,可能有bug:
/*
* Copyright (c) 2011 alexingcool. All Rights Reserved.
*/
#include <iostream>
#include <iterator>
#include <algorithm>
#define DEBUG
#undef DEBUG
using namespace std;
int array[] = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, -1, -2, -3};
const int size = sizeof array / sizeof *array;
void QuickSort(int (&array)[size]);
void _QuickSort(int (&array)[size], int start, int end);
int Partition(int (&array)[size], int start, int end);
int Partition2(int (&array)[size], int start, int end);
void QuickSort(int (&array)[size]) {
_QuickSort(array, 0, size - 1);
}
void _QuickSort(int (&array)[size], int start, int end) {
if(start < end) {
int pivot = Partition2(array, start, end);
_QuickSort(array, start, pivot - 1);
_QuickSort(array, pivot + 1, end);
}
}
int Partition(int (&array)[size], int start, int end) {
//别一个不小心写出 int pivot = array[end];
int& pivot = array[end];
int i = start - 1, j = start;
while(j < end) {
if(array[j] < pivot) {
i++;
swap(array[i], array[j]);
}
j++;
}
swap(array[i + 1], pivot);
return i + 1;
}
int Partition2(int (&array)[size], int start, int end) {
int& pivot = array[end];
int j = end - 1;
int i = start;
while(true) {
while(i < end && array[i] < pivot)
i++;
while(j > 0 && array[j] > pivot)
j--;
if(i > j)
break;
swap(array[i], array[j]);
}
swap(array[i], pivot);
#ifdef DEBUG
copy(array, array + size, ostream_iterator<int>(cout, " "));
system("pause");
#endif
return i;
}
void main() {
cout << "raw array: ";
copy(array, array + size, ostream_iterator<int>(cout, " "));
cout << endl;
QuickSort(array);
copy(array, array + size, ostream_iterator<int>(cout, " "));
cout << "finished" << endl;
}