1 /** 2 * 排序算法之归并排序 3 */ 4 #include <iostream> 5 #include <vector> 6 using namespace std; 7 8 void mergeKP(vector<int>& vec, int l1, int r1, int l2, int r2) { 9 int i = l1; 10 int j = l2; 11 int n = (r1 - l1 + 1) + (r2 - l2 + 1); 12 13 vector<int> temp(n); 14 int k = 0; 15 while (i <= r1 && j <= r2) { 16 if (vec[i] < vec[j]) { 17 temp[k++] = vec[i++]; 18 } else { 19 temp[k++] = vec[j++]; 20 } 21 } 22 while (i <= r1) { 23 temp[k++] = vec[i++]; 24 } 25 while (j <= r2) { 26 temp[k++] = vec[j++]; 27 } 28 for (int i = 0; i < n; i++) { 29 vec[l1 + i] = temp[i]; 30 } 31 } 32 33 void sortGuiBing(vector<int>& vec,int start, int end) { 34 if (start < end) { 35 int mid = (start + end) / 2; 36 sortGuiBing(vec, start, mid); 37 sortGuiBing(vec, mid + 1, end); 38 mergeKP(vec, start, mid, mid + 1, end); 39 } 40 } 41 int main() { 42 vector<int> vec = {2,1,3,5,4}; 43 int len = vec.size(); 44 sortGuiBing(vec, 0, len - 1); 45 for (int i = 0; i < len; ++i) { 46 cout << vec[i] << endl; 47 } 48 return 0; 49 }