合并排序的非递归算法

//合并排序的非递归算法
/*
合并排序:将待排序元素分成大小大致相同的两个子集合,分别对两个子集合进行排序
最终将排好序的子集合合并成所要求的排好序的集合
*/
#include


using namespace std;


void MergeSort(int a[], int n);
void Merge(int c[], int d[], int n, int m, int r);
void MergePass(int x[], int y[], int s, int n);


int main()
{
int array[14] = { 1,4,2,3,9,11,10,7,95,64,100,151,121,113 };


cout << "初始时,array里的元素顺序是:" << endl;
for (int i = 0; i < 14; i++)
{
cout << array[i] << ",";
}
cout << endl;
MergeSort(array, 14);
cout << "排序后,array里的元素顺序是:" << endl;
for (int i = 0; i < 14; i++)
{
cout << array[i] << ",";
}
cout << endl;


return 0;


}


//合并c[n:m]和c[m+1:r]到d[n:r]
void Merge(int c[], int d[], int n, int m, int r)
{
int i = n, j = m + 1, k = n;
while ((i <= m) && (j <= r))
{
if (c[i] <= c[j])
d[k++] = c[i++];
else
d[k++] = c[j++];
}
if (i > m)
{
for (int q = j; q <= r; q++)
d[k++] = c[q];
}
else
{
for (int q = i; q <= m; q++)
d[k++] = c[q];
}
}


void MergePass(int x[], int y[], int s, int n)
{//合并大小为s的相邻子数组
int i = 0;
while (i <= n - 2 * s)
{
//合并大小为s的相邻2段子数组
Merge(x, y, i, i + s - 1, i + 2 * s - 1);
i = i + 2 * s;
}
//剩下的元素个数少于2s
if (i + s < n)
Merge(x, y, i, i + s - 1, n - 1);
else
for (int j = i; j <= n - 1; j++)
y[j] = x[j];
}


void MergeSort(int a[], int n)
{
int *b = new int[n];
int s = 1;
while (s < n)
{
MergePass(a, b, s, n);//合并到数组b
s += s;
MergePass(b, a, s, n);//合并到数组a
s += s;
}

}


合并排序的非递归算法_第1张图片

你可能感兴趣的:(算法,算法,合并排序)