Merge_Sort C++
难点在于理解计算机执行顺序:
- 每次拆分(MergeSort)时,beg 和 end 的值
- 每次归并(Merge)时 L,R的内容
- 拆分的位置 在Merge_Sort退出时,带入Merge中
Merge_Sort.h
#include<vector>
#include<limits>
void Merge(std::vector<int>& A, int beg, int mid, int end) {
std::vector<int> L(A.cbegin() + beg, A.cbegin() + mid + 1);
std::vector<int> R(A.cbegin() + mid + 1, A.cbegin() + end + 1);
int i = 0, j = 0;
L.insert(L.end(), std::numeric_limits<int>::max());
R.insert(R.end(), std::numeric_limits<int>::max());
for (int k = beg; k <= end; k++)
{
if (L[i] < R[j])
A[k] = L[i++];
else
A[k] = R[j++];
}
}
void MergeSort(std::vector<int>& A, int beg, int end)
{
if (beg < end)
{
int mid = beg + (end - beg) / 2;
MergeSort(A, beg, mid);
MergeSort(A, mid + 1, end);
Merge(A, beg, mid, end);
}
}
main.cpp
#include"Merge_Sort.h"
#include<iostream>
using namespace std;
int main()
{
vector<int> arr = {38,27,43,3,9,82,10};
cout << "\n array is \n";
for (auto i : arr)
cout << i << " ";
cout << endl;
MergeSort(arr, 0, arr.size()-1);
cout << "\nSorted array is \n";
for (auto i : arr)
cout << i<<" ";
return 0;
}