快速排序的两种实现

来源:互联网 发布:python web.input 编辑:程序博客网 时间:2024/04/27 09:21

快速排序的两个实现,测试用例不多,可能有bug:

/** Copyright (c) 2011 alexingcool. All Rights Reserved.*/#include <iostream>#include <iterator>#include <algorithm>#define DEBUG#undef DEBUGusing 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 DEBUGcopy(array, array + size, ostream_iterator<int>(cout, " "));system("pause");#endifreturn 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;}


原创粉丝点击