有数组L,数组中数据值的序列为15,98,23,38,25,72,24使用冒泡排序的方法排序为升序的链表序列:15,23,24,25,38,72,98。
算法步骤:
假设初始序列含有n个记录,则可看成是n个有序的子序列,每个子序列的长度为1,然后两两归并,得到[n/2]个长度为2或1的有序的子序列,再两两归并,……,如此重复,直至得到一个长度为n的有序序列为止。
#include<iostream>
using namespace std;
//-------------------------------
void Merge(int R[],int T[],int low,int mid,int high)
{
int i=low;
int j=mid+1;
int k=low;
while(i<=mid&&j<=high)
{
if(R[i]<=R[j])
T[k++]=R[i++];
else T[k++]=R[j++];
}
while(i<=mid) T[k++]=R[i++];
while(j<=high) T[k++]=R[j++];
}
void MSort(int R[],int T[],int low,int high)
{
int S[7];
if(low==high) T[low]=R[high];
else
{
int mid = (low+high)/2;
MSort(R,S,low,mid);
MSort(R,S,mid+1,high);
Merge(S,T,low,mid,high);
}
}
void MergeSort(int L[])
{
MSort(L,L,0,6);
}
int main()
{
int L[7]={15,98,23,38,25,72,24};
cout<<"UnSort: ";
for(int i=0;i<7;i++)
{
cout<<L[i]<<" ";
}
cout<<endl;
MergeSort(L);
//----------------------
cout<<"Sort: ";
for( i=0;i<7;i++)
{
cout<<L[i]<<" ";
}
cout<<endl;
return 0;
}