#include <iostream> using namespace std; typedef int Element; inline bool Less(Element e1, Element e2) {return e1 < e2;} inline void Swap(Element* e1, Element* e2) { Element temp = *e1; *e1 = *e2; *e2 = temp; } int Partition(Element* eArray, int const left, int const right) { // j 以及j右边的元素不小于pivot;i以及i左边的元素不大于pivot; int pivotIndex = right; Element pivot = eArray[pivotIndex]; int i = left - 1; // 左扫描指针 int j = right; // 右扫描指针 // 从左往右扫描 while (i <= j) { // 寻早比pivot大的数据索引 while (Less(eArray[++i], pivot)) // 去掉i < j,因为可以保证eArray[++i]不会越界 { } while (Less(pivot, eArray[--j]) && j >= i) { } if (i >= j) { Swap(&eArray[i], &eArray[pivotIndex]); pivotIndex = i; break; } else { Swap(&eArray[i], &eArray[j]); } } return pivotIndex; } void QuickSort(Element* eArray, int const left, int const right) { if (left < right) // 单个元素的不排,只排包含两个以上元素的情况 { int pivotIndex = Partition(eArray, left, right); QuickSort(eArray, left, pivotIndex - 1); QuickSort(eArray, pivotIndex+1, right); } } int main() { int const size = 10; Element eArray[size] = {7, 2, 5, 8, 6, 0, 3, 1, 9, 4}; int i = 0; while (i < size) { cout << eArray[i++] << "/t"; // i == size的时候是没有输出的,所有用后缀i++,而不是++i; } cout << "/n"; QuickSort(eArray, 0, size-1); i = 0; while (i < size) { cout << eArray[i++] << "/t"; } cout << "/n"; return 0; }