标签:strong art font rand 不能 struct key while 分治法
必须要明白的: 分治法+挖坑填数;
分治法:大问题分解成各个小问题,对小问题求解,使得大问题得以解决。
1 #include<iostream> 2 #include<time.h> 3 #include<stdlib.h> 4 #include<sys/timeb.h> 5 using namespace std; 6 7 const int Max = 10; 8 9 void swap(int& a, int& b) { 10 int temp = a; 11 a = b; 12 b = temp; 13 } 14 15 long getSystemTime() { 16 struct timeb tb; 17 ftime(&tb); 18 return tb.time * 1000 + tb.millitm; 19 } 20 void Print(const int* arr, int length) { 21 for (int i = 0; i < length; i++) { 22 cout << arr[i] << " "; 23 } 24 } 25 void QuickSort(int* arr, int start, int end) { 26 int i = start; 27 int j = end; 28 //这里注意key不能为arr[0]; 29 int key = arr[start]; 30 if (i < j) { 31 while (i < j) { 32 while (i < j && arr[j] >= key) { 33 j--; 34 } 35 if (i < j) { 36 arr[i] = arr[j]; 37 i++; 38 } 39 while (i < j && arr[i] < key) 40 { 41 i++; 42 } 43 if (i < j) { 44 arr[j] = arr[i]; 45 j--; 46 } 47 } 48 //下面三行代码不能放在if语句的外面 49 arr[i] = key; 50 QuickSort(arr, start, i - 1); 51 QuickSort(arr, i + 1, end); 52 } 53 54 } 55 56 int main() { 57 int arr[Max]; 58 srand((unsigned)time(NULL)); 59 for (int i = 0; i < Max; i++) { 60 arr[i] = rand() % Max; 61 } 62 cout << "排序前:\n"; 63 Print(arr, Max); 64 long pt = getSystemTime(); 65 QuickSort(arr, 0, Max - 1); 66 long at = getSystemTime(); 67 cout << "\n排序后:\n"; 68 Print(arr, Max); 69 70 cout << "\ntime of sort:" << at - pt << "ms\n"; 71 72 73 return 0; 74 }
标签:strong art font rand 不能 struct key while 分治法
原文地址:https://www.cnblogs.com/jibisheng/p/12994886.html