#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
int min(int a, int b)
{
return a < b ? a : b;
}
void merge(vector<int> &arry, int start, int mid, int end, vector<int> &backup)
{
int i = start;
int j = mid;
for (int idx = start; idx < end; ++ idx)
{
if (i < mid && (j >= end || arry[i] <= arry[j]))
backup[idx] = arry[i++];
else
backup[idx] = arry[j++];
}
}
void mergeSort(vector<int> &arry)
{
auto n = arry.size();
vector<int> backup(n);
for (int width = 1; width <= n; width *= 2)
{
for (int i = 0; i < n; i += (width * 2))
{
merge(arry, i, min(i + width, n), min(i + (2 * width), n), backup);
}
copy(backup.begin(), backup.end(), arry.begin());
}
}
int main(int argc, const char * argv[]) {
vector<int> vi {10, 3, 4, 8, 9};
mergeSort(vi);
for (auto a : vi)
cout << a << endl;
return 0;
}
Merge Sort (O(nlogn))
最新推荐文章于 2024-08-13 09:54:25 发布