快速排序【代码】
思路参考《算法导论》P95
这里有位老哥的文章写的挺形象的呀
http://developer.51cto.com/art/201403/430986.htm
我是参照书上实现的,觉得挺简单的
-------------------------------------------------------代码-------------------------------------------------------
1 // QUICKSORT.cpp: 定义控制台应用程序的入口点。 2 // 3 4 #include "stdafx.h" 5 #include <iostream> 6 #include <random> 7 8 using namespace std; 9 10 int PARTITION(int *A, int p, int r) 11 { 12 int x = A[r]; 13 int i = p - 1; 14 int temp; 15 for (int j = p; j < r; j++) 16 { 17 if (A[j] <= x) 18 { 19 i++; 20 temp = A[i]; 21 A[i] = A[j]; 22 A[j] = temp; 23 } 24 } 25 temp = A[i+1]; 26 A[i+1] = A[r]; 27 A[r] = temp; 28 return i+1; 29 } 30 31 int QUICKSORT(int *A,int p,int r) 32 { 33 if (p < r) 34 { 35 int q = PARTITION(A,p,r); 36 QUICKSORT(A, p, q - 1); 37 QUICKSORT(A, q + 1, r); 38 } 39 return 0; 40 } 41 42 //------------------------------随机化版本-------------------------------- 43 44 int RANDOM_PARTITION(int *A, int p, int r) 45 { 46 uniform_int_distribution<unsigned> u(p,r); 47 default_random_engine e; 48 int i = u(e);//生成[p,r]之间的随机数 49 int temp = A[i]; 50 A[i] = A[r]; 51 A[r] = temp; 52 return PARTITION(A,p,r); 53 } 54 55 int RANDOM_QUICKSORT(int *A, int p, int r) 56 { 57 if (p < r) 58 { 59 int q = RANDOM_PARTITION(A, p, r); 60 RANDOM_QUICKSORT(A, p, q - 1); 61 RANDOM_QUICKSORT(A, q + 1, r); 62 } 63 return 0; 64 } 65 66 67 int main() 68 { 69 int A[] = { 2,8,7,1,3,5,6,4 }; 70 int B[] = { 2,8,7,1,3,5,6,4 }; 71 for (auto c : A) 72 cout << c << ends; 73 cout << endl; 74 75 QUICKSORT(A,0,7); 76 for (auto c : A) 77 cout << c << ends; 78 cout << endl; 79 80 RANDOM_QUICKSORT(B, 0, 7); 81 for (auto c : B) 82 cout << c << ends; 83 cout << endl; 84 return 0; 85 }
运行结果:
只有0和1的世界是简单的