#include<iostream>
#include<memory>
using namespace std;
void merger_in(int arr[], int low, int high, int mid)
{
int lengh = high - low + 1;
int* parr = new int[lengh];//分配辅助空间
memset(parr, 0, sizeof(int)*lengh);//初始化为零
int left = low;//设置左右"指针"
int right = mid+1;
int index = 0;
while (right <= high&&left <= mid)//当"指针都满足条件"进循环
{
if (arr[left]<=arr[right])//如果满足升序将左边的数填入辅助空间,指针移动
{
parr[index] = arr[left];
index++;
left++;
}
else
{
parr[index] = arr[right];//不满足将右边的数填入辅助空间
index++;
right++;
}
}
if (left <= mid)//假如右边指针先到头/将左边剩余数据填入辅助空间
memmove(&parr[index], &arr[left], sizeof(int)*(mid - left+ 1));
if (right <= high)//假如左边指针先到头/将右边剩余数据填入辅助空间
memmove(&parr[index], &arr[right], sizeof(int)*(high - right + 1));
memmove(&arr[low], parr, sizeof(int)*lengh);//最后将辅助空间内的数据返回到原空间
delete[]parr;//释放堆内存
}
void merger_back(int arr[], int low, int high)//递归二分
{
if (low >= high)
return;
int mid = (low + high) >> 1;
merger_back(arr, low, mid);//左半边
merger_back(arr, mid + 1, high);//右半边
merger_in(arr, low, high, mid);//递归合并
}
void merger(int arr[], int low, int high)//归并排序
{
merger_back (arr, low, high);//递归
}
int main()
{
int arr[] = { 32, 15, 3, 1, 7, 45, 6, 5, 545, 5 };
merger(arr, 0, 9);
for (int i = 0; i < 10; ++i)
cout << arr[i] << endl;
system("pause");
return 0;
#include<memory>
using namespace std;
void merger_in(int arr[], int low, int high, int mid)
{
int lengh = high - low + 1;
int* parr = new int[lengh];//分配辅助空间
memset(parr, 0, sizeof(int)*lengh);//初始化为零
int left = low;//设置左右"指针"
int right = mid+1;
int index = 0;
while (right <= high&&left <= mid)//当"指针都满足条件"进循环
{
if (arr[left]<=arr[right])//如果满足升序将左边的数填入辅助空间,指针移动
{
parr[index] = arr[left];
index++;
left++;
}
else
{
parr[index] = arr[right];//不满足将右边的数填入辅助空间
index++;
right++;
}
}
if (left <= mid)//假如右边指针先到头/将左边剩余数据填入辅助空间
memmove(&parr[index], &arr[left], sizeof(int)*(mid - left+ 1));
if (right <= high)//假如左边指针先到头/将右边剩余数据填入辅助空间
memmove(&parr[index], &arr[right], sizeof(int)*(high - right + 1));
memmove(&arr[low], parr, sizeof(int)*lengh);//最后将辅助空间内的数据返回到原空间
delete[]parr;//释放堆内存
}
void merger_back(int arr[], int low, int high)//递归二分
{
if (low >= high)
return;
int mid = (low + high) >> 1;
merger_back(arr, low, mid);//左半边
merger_back(arr, mid + 1, high);//右半边
merger_in(arr, low, high, mid);//递归合并
}
void merger(int arr[], int low, int high)//归并排序
{
merger_back (arr, low, high);//递归
}
int main()
{
int arr[] = { 32, 15, 3, 1, 7, 45, 6, 5, 545, 5 };
merger(arr, 0, 9);
for (int i = 0; i < 10; ++i)
cout << arr[i] << endl;
system("pause");
return 0;
}
运行结果如下: