1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
| // 快速排序.cpp: 定义控制台应用程序的入口点。 //
#include "stdafx.h" #include <iostream> #include <cstdlib> #include <ctime> using namespace std;
#define MAX_SIZE 20
int Partition(int a[], int start, int end) { if (start >= end) return start; int pivotkey = a[start]; while (start < end) { while (start < end && a[end] >= pivotkey) end--; a[start] = a[end]; while (start < end && a[start] < pivotkey) start++; a[end] = a[start]; } a[start] = pivotkey; return start; }
void QuickSort(int a[], int start, int end) { if (start < end) { int p = Partition(a, start, end); QuickSort(a, start, p - 1); QuickSort(a, p + 1,end); } } int main() { srand(time(0)); int a[MAX_SIZE]; for (int i = 0; i < MAX_SIZE; i++) a[i] = rand() % MAX_SIZE + 1; for (int i = 0; i < MAX_SIZE; i++) { cout << a[i] << " "; } cout << endl; QuickSort(a, 0, MAX_SIZE - 1); for (int i= 0;i<MAX_SIZE;i++) { cout << a[i] << " "; } cout << endl; return 0; }
|