merge sort
reference: https://blog.csdn.net/zpznba/article/details/83745205
It's post-order traversal.
#include <iostream>
#include <vector>
using namespace std;
void mergeHelper(vector<int> &nums, int left, int mid, int right) {
vector<int> vec(right - left + 1);
int index = 0;
int i=left;
int j=mid+1;
while(i<=mid && j<=right) {
vec[index++] = nums[i] < nums[j] ? nums[i++] : nums[j++];
}
while(i<=mid) {
vec[index++] = nums[i++];
}
while(j<=right) {
vec[index++] = nums[j++];
}
for(int i=0; i<right-left+1; i++) {
nums[left+i] = vec[i];
}
}
void mergeSort(vector<int> &nums, int left, int right) {
if (left == right) {
return;
}
int mid = left + (right - left)/2;
mergeSort(nums, left, mid);
mergeSort(nums, mid+1, right);
mergeHelper(nums, left, mid, right);
}
int main()
{
vector<int> nums = {9,7,4,2,6,5};
mergeSort(nums, 0 ,nums.size() - 1);
for (int i=0; i<nums.size(); i++) {
cout<<nums[i]<<endl;
}
return 0;
}
quick sort
reference: https://wiki.jikexueyuan.com/project/easy-learn-algorithm/fast-sort.html
It's pre-order traversal.
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
void quickSort(vector<int> &nums, int left, int right) {
if (left > right) {
return;
}
int num = nums[left];
int i=left;
int j=right;
while(i<j) {
while (i<nums.size() && nums[i]<num) {
i++;
}
while (j>0 && nums[j]>num) {
j--;
}
swap(nums[i], nums[j]);
}
swap(num, nums[i]);
quickSort(nums, left, i-1);
quickSort(nums, i+1, right);
}
int main()
{
vector<int> nums = {9,7,4,2,6,5};
quickSort(nums, 0 ,nums.size() - 1);
for (int i=0; i<nums.size(); i++) {
cout<<nums[i]<<endl;
}
return 0;
}