常见排序算法之归并排序的C++实现 #include<iostream> #include<vector> #include<algorithm> using namespace std; vector<int> vtmp; class Solution { public: void mergeSort(vector<int>& v, int left, int right) { if (v.size() <= 1 || left >= right) return; int mid = left + (right - left) / 2; mergeSort(v, left, mid); mergeSort(v, mid + 1, right); merge(v, left, mid, right); } void merge(vector<int>& v, int left, int mid, int right) { int i = left, j = mid + 1, k = left; while (i <= mid && j <= right) { if (v[i] <= v[j]) vtmp[k++] = v[i++]; else vtmp[k++] = v[j++]; } while (i <= mid) vtmp[k++] = v[i++]; while (j <= right) vtmp[k++] = v[j++]; for (int a = left; a <= right; ++a) v[a] = vtmp[a]; } }; int main() { Solution so; vector<int> v = { 10, 2, 9, 1, 7, 0, 4, 3, 5, 8, 6 }; //vector<int> v1 = { 0, 1, 0, 1, 2, 2, 3, 1, 0, 1, 2, 3, 1, 2, 3 }; vtmp.resize(v.size()); for (int x : v) cout << x << " "; cout << endl; so.mergeSort(v, 0, v.size() - 1); for (int x : v) cout << x << " "; return 0; }