标签:
void mergesort(int []array1, int low, int high)
{
if (low < high)
{
int middle = (low + high) / 2;
mergesort(array1, low, middle);//排序左半部分
mergesort(array1, middle + 1, high);//排序右半部分
merge(array1, low, middle, high);//归并
}
}
void merge(int []array1, int low, int middle, int high)
{
int helper[]=new int[array1.length];
/*将数组左右两半拷贝到helper数组中*/
for (int i = low; i <= high; i++)
{
helper[i] = array1[i];
}
int helperLeft = low;
int helperRight = middle + 1;
int current = low;
/*迭代访问helper数组,比较左右两半的元素,
并将较小的元素复制到原先的数组中*/
while (helperLeft <= middle&&helperRight <= high)
{
if (helper[helperLeft] <= helper[helperRight])
{
array1[current] = helper[helperLeft];
helperLeft++;
}
else
{
array1[current] = helper[helperRight];
helperRight++;
}
current++;
}
/*将数组左半部分剩余元素复杂到目标数组中*/
int remaining = middle - helperLeft;
for (int i = 0; i <= remaining; i++)
{
array1[current + i] = helper[helperLeft + i];
}
}
public static void mergesort(int[] array1)
{
int[] helper = new int[array1.length];
mergesort(array1, helper, 0, array1.length - 1);
}
c++版:
#include<iostream>
using namespace std;
void merge(int array1[], int low, int middle, int high)
{
int len = high - low+1;
int *helper = new int[len];
/*将数组左右两半拷贝到helper数组中*/
for (int i = low; i <= high; i++)
{
helper[i] = array1[i];
}
int helperLeft = low;
int helperRight = middle + 1;
int current = low;
/*迭代访问helper数组,比较左右两半的元素,
并将较小的元素复制到原先的数组中*/
while (helperLeft <= middle&&helperRight <= high)
{
if (helper[helperLeft] <= helper[helperRight])
{
array1[current] = helper[helperLeft];
helperLeft++;
}
else
{
array1[current] = helper[helperRight];
helperRight++;
}
current++;
}
/*将数组左半部分剩余元素复杂到目标数组中*/
int remaining = middle - helperLeft;
for (int i = 0; i <= remaining; i++)
{
array1[current + i] = helper[helperLeft + i];
}
}
void mergesort(int array1[], int low, int high)
{
if (low < high)
{
int middle = (low + high) / 2;
mergesort(array1, low, middle);//排序左半部分
mergesort(array1, middle + 1, high);//排序右半部分
merge(array1, low, middle, high);//归并
}
}
void main()
{
int n = 6;
int *array1 = new int[n];
cout << "please input the number:" << endl;
for (int i = 0; i < n; ++i)
{
cin>> array1[i];
}
mergesort(array1, 0, n- 1);
for (int i = 0; i < n; ++i)
{
cout << array1[i];
}
system("pause");
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:
原文地址:http://blog.csdn.net/wangfengfan1/article/details/47667705