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 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158
| class Solution { public: vector<int> sortArray(vector<int>& nums) {
head_sort(0, nums.size() - 1, nums); return nums; }
void head_sort(int st, int ed, vector<int>& nums) { buildMaxHeap(nums);
int len = nums.size(); for(int ed = len - 1; ed >= 0; --ed) { swap(st, ed, nums); maxHeapify(st, ed - 1, nums); } }
void buildMaxHeap(vector<int>& nums) { int len = nums.size(); for(int dad = len / 2 - 1; dad >= 0; --dad) { maxHeapify(dad, len - 1, nums); } }
void maxHeapify(int st, int ed, vector<int>& nums) { if(ed <= st) { return; }
while(st <= ed) { int lChild = st * 2 + 1; int rChild = st * 2 + 2; if(lChild > ed) { return; } else if(rChild > ed) { if(nums[st] < nums[lChild]) { swap(st, lChild, nums); } return; } if(nums[st] >= nums[lChild] && nums[st] >= nums[rChild]) { return; } else { if(nums[lChild] > nums[rChild]) { swap(st, lChild, nums); st = lChild; } else { swap(st, rChild, nums); st = rChild; } } } }
void mergeSort(int st, int ed, vector<int>& nums) { if(ed - st == 1) { if(nums[ed] < nums[st]) { swap(ed, st, nums); } return; } else if(ed == st) { return; } int mid = (st + ed) / 2; cout << mid << endl; mergeSort(st, mid, nums); mergeSort(mid + 1, ed, nums); int curL = 0; int curR = 0; vector<int> tmpL(nums.begin() + st, nums.begin() + mid + 1); vector<int> tmpR(nums.begin() + mid + 1, nums.begin() + ed + 1);
for(int i = st; i <= ed; ++i) { if(curL == mid - st + 1) { for(; curR < ed - mid; ++curR) { nums[i++] = tmpR[curR]; } break; } else if(curR == ed - mid) { for(; curL < mid - st + 1; ++curL) { nums[i++] = tmpL[curL]; } break; } else if(tmpL[curL] < tmpR[curR]) { nums[i] = tmpL[curL++]; } else { nums[i] = tmpR[curR++]; } } }
void quickSort(int st, int ed, vector<int>& nums) { if(st >= ed) { return; } int newPivot = partition(st, ed, nums); quickSort(st, newPivot-1, nums); quickSort(newPivot + 1, ed, nums); }
int partition(int st, int ed, vector<int>& nums) { int r = ed; int l = st; int pivot = nums[st]; while(l < r){ while(r > l && nums[r] > pivot) { r--; } nums[l] = nums[r];
while(l < r && nums[l] <= pivot) { l++; } nums[r] = nums[l]; } nums[l] = pivot; return l; }
void swap(int& a, int& b, vector<int>& nums) { int tmp = nums[a]; nums[a] = nums[b]; nums[b] = tmp; }
void print(vector<int>& nums) { for(auto& i : nums) { cout << i << " "; } cout << "\n"; } };
|