1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
| /** * <归并排序> * 时间复杂度: 最好O(n*log(n)) 最坏O(n*log(n)) 平均O(n*log(n)) 稳定 * 空间复杂度: O(n) */ class Solution { public: vector<int> aux; vector<int> sortArray(vector<int>& nums) { aux.resize(nums.size()); _sortArray(nums, 0, nums.size() - 1); return nums; } void _sortArray(vector<int>& nums, int lo, int hi) { if(hi <= lo) return ; int mid = lo + (hi - lo) / 2; _sortArray(nums,lo ,mid); _sortArray(nums, mid + 1, hi); merge(nums, lo, mid, hi); } void merge(vector<int>& nums, int lo, int mid, int hi) { int i = lo, j = mid + 1; for(int k = lo; k <= hi; ++k) aux[k] = nums[k]; for(int k = lo; k <= hi; ++k) { if(i > mid) nums[k] = aux[j++]; else if (j > hi) nums[k] = aux[i++]; else if (aux[i] < aux[j]) nums[k] = aux[i++]; else nums[k] = aux[j++]; } } };
//自底向上 class Solution { public: vector<int> aux; vector<int> sortArray(vector<int>& nums) { aux.resize(nums.size()); for(int sz = 1; sz < nums.size(); sz = 2 * sz) for(int lo = 0; lo < nums.size(); lo += sz + sz) merge(nums, lo, lo + sz - 1, min(lo + sz + sz - 1, (int)nums.size() - 1)); return nums; } void merge(vector<int>& nums, int lo, int mid, int hi) { int i = lo, j = mid + 1; for(int k = lo; k <= hi; ++k) aux[k] = nums[k]; for(int k = lo; k <= hi; ++k) { if(i > mid) nums[k] = aux[j++]; else if (j > hi) nums[k] = aux[i++]; else if (aux[i] < aux[j]) nums[k] = aux[i++]; else nums[k] = aux[j++]; } } };
|