//归并排序算法的非递归实现
#include <iostream>
using namespace std;
#define MAX 65535
void MergeSort(int source_array[], int Len);
void MergePass(int source_array[], int des_array[], int k, int Len);
void Merge(int source_array[], int des_array[], int start, int mid, int end);
int main()
{
int N=10;
int array[10] = { 4, 3, 7, 8, 0, 9, 1, 2, 6, 5 };
MergeSort(array, N);
for (int i = 0; i<N; i++)
{
cout<< array[i]<<“,”;
}
system(“pause”);
return 0;
}
void MergeSort(int source_array[], int Len)
{
int k = 1;
int des_array[MAX];
while (k<Len)
{
MergePass(source_array, des_array, k, Len);
k = 2 * k;}
}
void MergePass(int source_array[], int des_array[], int k, int Len) //把source_array[]中的相邻长为k的子序列归并到des_array[]中
{
int i = 0;
while (i + 2 * k <= Len)
{
Merge(source_array, des_array, i, i + k – 1, i + 2 * k – 1);
i += 2 * k;
}
if (i + k-1 < Len)
//归并最后两个序列
(当k>1且分组的个数为奇数时会执行此处)
Merge(source_array, des_array, i, i + k – 1, Len-1);
else
//若最后只剩下单个子序列
for (int j = i; j < Len; j++)
{
des_array[j] = source_array[j];
}
for (int j = 0; j<Len; j++) //排序原序列的中的数值
{
source_array[j] = des_array[j];
}
}
void Merge(int source_array[], int des_array[], int start, int mid, int end)
{
int i = start, j = mid + 1;
int k = start;
while (i<=mid&&j<=end)
{
if (source_array[i] > source_array[j])
des_array[k++] = source_array[j++];
else
des_array[k++] = source_array[i++];
}
while (i<=mid)
{
des_array[k++] = source_array[i++];
}
while (j <= end)
{
des_array[k++] = source_array[j++];
}
}