#include<iostream>
#include<cstdlib>
using namespace std;
#define MAXSIZE 20
typedef int ElemType;
typedef struct{
ElemType Array[MAXSIZE + 1];//Array[0]置哨
int length;
}SqList;
void Merge(ElemType S[], ElemType T[], int i, int m, int n)//归并基程序
{//对S[i...m]和T[m+1...n]这两个有序表归并成一个有序表
int j = m + 1, k = i;
while (i <= m&&j <= n)
{
if (S[i] <= S[j]) T[k++] = S[i++];
else T[k++] = S[j++];
}
if (i <= m)
while (k <= n&&i <= m) T[k++] = S[i++];//k<=n一定成立,所有可有可无
if (j <= n)
while (k <= n&&j <= n) T[k++] = S[j++];//k<=n一定成立,所有可有可无
}
void MSort(ElemType S[], ElemType T[], int s, int t)//递归归并
{
int m;
ElemType R[20];
if (s == t)
T[s] = S[s];//只有一个元素
else
{//多个元素
m = (s + t) / 2;//一分为二
MSort(S, R, s, m);//递归左区间使左区间为一有序子表
MSort(S, R, m + 1, t);//递归右区间使右区间为一有序子表
Merge(R, T, s, m, t);//归并左右两有序子表为一个有序表
}
}
void MergeSort(SqList &L)//归并排序
{
MSort(L.Array, L.Array, 1, L.length);
}
int main(void)
{
SqList L; int i;
cout << "The length of LIST :"; cin >> L.length;
cout << "enter nodes:" << endl;
for (i = 1; i <= L.length; i++)
cin >> L.Array[i];
for (i = 1; i <= L.length; i++)
cout << L.Array[i] << " ";
cout << endl;
MergeSort(L);
for (i = 1; i <= L.length; i++)
cout << L.Array[i] << " ";
cout << endl;
return(0);
}
数据结构之归并排序(递归实现)
最新推荐文章于 2024-12-28 23:34:57 发布