#include<iostream>
#include<vector>
using namespace std;
void merge(vector<int>& nums, int l, int mid, int r)
{
vector<int> left_nums;
vector<int> right_nums;
for (int i = l; i <= mid; i++)
{
left_nums.push_back(nums[i]);
}
for (int j = mid + 1; j <= r; j++)
{
right_nums.push_back(nums[j]);
}
int l_cur = 0;
int r_cur = 0;
int l_size=left_nums.size();
int r_size = right_nums.size();
int nums_cur = l;
while ((l_cur <= (l_size - 1)) && (r_cur <= (r_size - 1)))
{
if (left_nums[l_cur] <= right_nums[r_cur])
{
nums[nums_cur] = left_nums[l_cur];
l_cur++;
nums_cur++;
}
else
{
nums[nums_cur] = right_nums[r_cur];
r_cur++;
nums_cur++;
}
}
if (l_cur > (l_size-1))
{
while (r_cur <= (r_size-1))
{
nums[nums_cur] = right_nums[r_cur];
nums_cur++;
r_cur++;
}
}
if (r_cur > (r_size - 1))
{
while (l_cur <= (l_size-1))
{
nums[nums_cur] = left_nums[l_cur];
nums_cur++;
l_cur++;
}
}
}
void merge_sort(vector<int>& nums, int l,int r)
{
int mid = (l + r) / 2;
if (mid+1<r)//如果左边需要排序那么就对左边做归并排序
{
merge_sort(nums, mid + 1, r);
}
if (l < mid)//如果右边需要排序那么对右边归并排序
{
merge_sort(nums,l, mid);
}
merge(nums, l, mid, r);//左右都有序了就合并
}
int main()
{
vector<int> nums;
int n;
cout << "input n"<<endl;
cin >> n;
cout << "nums" << endl;
for (int i = 0; i < n; i++)
{
int temp;
cin >> temp;
nums.push_back(temp);
}
merge_sort(nums, 0, nums.size()-1);
for (int i = 0; i < nums.size(); i++)
{
cout << nums[i] << ' ';
}
return 0;
}
#include<vector>
using namespace std;
void merge(vector<int>& nums, int l, int mid, int r)
{
vector<int> left_nums;
vector<int> right_nums;
for (int i = l; i <= mid; i++)
{
left_nums.push_back(nums[i]);
}
for (int j = mid + 1; j <= r; j++)
{
right_nums.push_back(nums[j]);
}
int l_cur = 0;
int r_cur = 0;
int l_size=left_nums.size();
int r_size = right_nums.size();
int nums_cur = l;
while ((l_cur <= (l_size - 1)) && (r_cur <= (r_size - 1)))
{
if (left_nums[l_cur] <= right_nums[r_cur])
{
nums[nums_cur] = left_nums[l_cur];
l_cur++;
nums_cur++;
}
else
{
nums[nums_cur] = right_nums[r_cur];
r_cur++;
nums_cur++;
}
}
if (l_cur > (l_size-1))
{
while (r_cur <= (r_size-1))
{
nums[nums_cur] = right_nums[r_cur];
nums_cur++;
r_cur++;
}
}
if (r_cur > (r_size - 1))
{
while (l_cur <= (l_size-1))
{
nums[nums_cur] = left_nums[l_cur];
nums_cur++;
l_cur++;
}
}
}
void merge_sort(vector<int>& nums, int l,int r)
{
int mid = (l + r) / 2;
if (mid+1<r)//如果左边需要排序那么就对左边做归并排序
{
merge_sort(nums, mid + 1, r);
}
if (l < mid)//如果右边需要排序那么对右边归并排序
{
merge_sort(nums,l, mid);
}
merge(nums, l, mid, r);//左右都有序了就合并
}
int main()
{
vector<int> nums;
int n;
cout << "input n"<<endl;
cin >> n;
cout << "nums" << endl;
for (int i = 0; i < n; i++)
{
int temp;
cin >> temp;
nums.push_back(temp);
}
merge_sort(nums, 0, nums.size()-1);
for (int i = 0; i < nums.size(); i++)
{
cout << nums[i] << ' ';
}
return 0;
}