归并排序
1 #include <vector> 2 #include <iostream> 3 4 using namespace std; 5 6 void Merge(vector<int>& data, vector<int>& temp, int left, int right, int mid) { 7 8 int i = left, j = mid + 1, k = left; 9 while (i <= mid && j <= right) { 10 if (data[i] >= data[j]) 11 temp[k++] = data[i++]; 12 else 13 temp[k++] = data[j++]; 14 } 15 16 while (i <= mid) 17 temp[k++] = data[i++]; 18 19 while (j <= right) 20 temp[k++] = data[j++]; 21 22 for (i = left; i <= right; ++i) 23 data[i] = temp[i]; 24 25 } 26 27 void MergeSort(vector<int>& data, vector<int>& temp, int left, int right) { 28 29 int mid = left + (right - left) / 2; 30 if (left >= right) 31 return; 32 else { 33 MergeSort(data, temp, left, mid); 34 MergeSort(data, temp, mid + 1, right); 35 Merge(data, temp, left, right, mid); 36 } 37 38 } 39 40 41 int main() { 42 43 vector<int> data{ 12,13,0,21,10,5,7 }; 44 vector<int> t(7); 45 46 MergeSort(data, t, 0, 6); 47 48 for (int i = 0; i < 7; i++) 49 cout << t[i] << " "; 50 51 52 return 0; 53 }