#include "pch.h"
#include <iostream>
#include<algorithm>
using namespace std;
const int maxn = 100;
//将数组A的[L1,R1]和[L2,R2]区间合并为有序区间(此处的L2即为R1+1)
void merge(int A[], int L1, int R1, int L2, int R2)
{
int i = L1, j =L2;
int temp[maxn], index = 0;
while (i<=R1&&j<=R2)
{
if (A[i] < A[j])
{
temp[index++] = A[i++];
}
else
{
temp[index++] = A[j++];
}
}
while (i<=R1)
{
temp[index++] = A[i++];
}
while (j<=R2)
{
temp[index++] = A[j++];
}
for (int i = 0; i < index; i++) {
A[L1 + i] = temp[i];
}
}
//将array数组当前区间[left,right]进行归并排序【递归实现版本】
void mergeSort(int A[], int left, int right)
{
if (left < right)
{
int mid = (left + right) / 2;
mergeSort(A, left, mid);
mergeSort(A, mid+1, right);
merge(A, left, mid, mid + 1, right);
}
}
//【非递归实现版本】
int n;
void mergrSort(int A[])
{
//step为组内元素个数,step/2为左子区间元素个数,注意等号可以不取
for (int step = 2; step / 2 <= n; step *= 2)
{
for (int i = 1; i <= n; i += step)
{
int mid = i + step / 2 - 1;
if (mid + 1 <= n) {
merge(A, i, mid, mid + 1, min(i + step - 1, n));
}
}
}
}
void mergeSort_(int A[])
{
for (int step = 2; step / 2 <= n; step *= 2)
{
for (int i = 1; i <= n; i += step)
{
sort(A + i, A + min(i + step, n + 1));
}
}
}