归并排序(Mergesort)是建立在归并操作上的一种有效的排序算法。该算法是采用分治法(DivideandConquer)的一个非常典型的应用。
代码实现:
#include <iostream> #include <vector> using namespace std; void mergeSort(vector<int>& nums, int l, int r) { if (l >= r) { return; } int mid = (l + r) / 2; mergeSort(nums, l, mid); mergeSort(nums, mid + 1, r); vector<int> temp(r - l + 1); int i = l, j = mid + 1, k = 0; while (i <= mid && j <= r) { if (nums[i] < nums[j]) { temp[k++] = nums[i++]; } else { temp[k++] = nums[j++]; } } while (i <= mid) { temp[k++] = nums[i++]; } while (j <= r) { temp[k++] = nums[j++]; } for (int i = l; i <= r; ++i) { nums[i] = temp[i - l]; } } int main() { vector<int> nums {5, 1, 9, 3, 7, 4, 8, 6, 2}; mergeSort(nums, 0, nums.size() - 1); for (auto num : nums) { cout << num << " "; } return 0; }