1.实现
#include <iostream> #include <vector> using namespace std; template<class T> void merge(vector<T>& a, int left, int mid, int right) { vector<T> temp(right - left + 1); int left_begin = left; int right_begin = mid + 1; int i = 0; while (left_begin <= mid && right_begin <= right) { if (a[left_begin] < a[right_begin]) { temp[i++] = a[left_begin++]; } else { temp[i++] = a[right_begin++]; } } while (left_begin <= mid) { temp[i++] = a[left_begin++]; } while (right_begin <= right) { temp[i++] = a[right_begin++]; } for (int i = left; i <= right; ++i) { a[i] = temp[i - left]; } } template<class T> void merge_sort(vector<T>& a, int begin, int end) { if (begin < end) { int mid = begin + (end - begin) / 2; merge_sort(a, begin, mid); merge_sort(a, mid + 1, end); merge(a, begin, mid, end); } } int main() { vector<int>a{ 1,3,4,9,2,6,7,8 }; merge_sort(a, 0, 7); for (auto i : a) cout << i << " "; cout << endl; }
2.性能分析
稳定性:稳定
时间复杂度:O(n*logn)
空间复杂度:O(n)
最坏时间复杂度:O(n*logn)