@@ -222,4 +222,69 @@ function merge($left, $right)
222
222
223
223
return $result;
224
224
}
225
+ ```
226
+
227
+ ## 9. C++ 代码实现
228
+
229
+ ### 9.1 递归版
230
+
231
+ ``` cpp
232
+ void mergeSort (vector<int >& nums, int l, int r) {
233
+ if (r - l <= 1) {
234
+ return;
235
+ }
236
+ int mid = (l + r) / 2;
237
+ mergeSort(nums, l, mid);
238
+ mergeSort(nums, mid, r);
239
+ int index = 0;
240
+ int ptrL = l;
241
+ int ptrR = mid;
242
+ static vector<int >tempary(50000);
243
+ while (ptrL != mid && ptrR != r) {
244
+ if (nums[ ptrL] < nums[ ptrR] ) {
245
+ tempary[ index++] = nums[ ptrL++] ;
246
+ } else {
247
+ tempary[ index++] = nums[ ptrR++] ;
248
+ }
249
+ }
250
+ while (ptrL != mid) {
251
+ tempary[ index++] = nums[ ptrL++] ;
252
+ }
253
+ while (ptrR != r) {
254
+ tempary[ index++] = nums[ ptrR++] ;
255
+ }
256
+ copy(tempary.begin(), tempary.begin() + index, nums.begin() + l);
257
+ }
258
+ ```
259
+
260
+ ### 9.2 迭代版
261
+
262
+ ```cpp
263
+ void mergeSort(vector<int>& nums) {
264
+ for (int step = 1; step <= nums.size(); step *= 2) {
265
+ for (int i = 0; i + step < nums.size(); i += 2 * step) {
266
+ int l = i;
267
+ int r = min((int)nums.size(), i + step * 2);
268
+ int mid = i + step;
269
+ int index = 0;
270
+ int ptrL = l;
271
+ int ptrR = mid;
272
+ static vector<int>tempary(50000);
273
+ while (ptrL != mid && ptrR != r) {
274
+ if (nums[ptrL] < nums[ptrR]) {
275
+ tempary[index++] = nums[ptrL++];
276
+ } else {
277
+ tempary[index++] = nums[ptrR++];
278
+ }
279
+ }
280
+ while (ptrL != mid) {
281
+ tempary[index++] = nums[ptrL++];
282
+ }
283
+ while (ptrR != r) {
284
+ tempary[index++] = nums[ptrR++];
285
+ }
286
+ copy(tempary.begin(), tempary.begin() + index, nums.begin() + l);
287
+ }
288
+ }
289
+ }
225
290
```
0 commit comments