#include<iostream>
#include<cstdlib>
using namespace std;
//归并子序列
void Merge(int A[],int Temp[],int Left,int Right,int RightEnd){
int LeftEnd;
int index;
LeftEnd = Right - 1;
index = Left;
int Num = RightEnd - Left + 1;
while( (Left <= LeftEnd ) && (Right <= RightEnd) ){
if( A[Left] <= A[Right] ){
Temp[index++] = A[Left++];
}
else{
Temp[index++] = A[Right++];
}
}
//将剩余的元素移到Temp中
while(Left<=LeftEnd){
Temp[index++] = A[Left++];
}
while(Right<=RightEnd){
Temp[index++] = A[Right++];
}
for(int i = 0;i < Num; i++ , RightEnd-- ){
A[RightEnd] = Temp[RightEnd];
}
}
//递归排序
void MSort(int A[],int Temp[],int Left,int RightEnd)
{
int center = (Left+RightEnd)/2;
if(Left < RightEnd){
MSort(A,Temp,Left,center);//递归排序左边
MSort(A,Temp,center+1,RightEnd);//
Merge(A,Temp,Left,center+1,RightEnd);
}
}
void MergeSort(int A[],int N){
int *Temp = new int[N];
MSort(A,Temp,0,N-1);
delete []Temp;
}
int main(){
int A[10] = {5,6,8,1,7,3,2,9,2,4};
for(int i=0;i<10;i++){
cout<<A[i]<<" ";
}
MergeSort(A,10);
cout<<"\n";
for(int i=0;i<10;i++){
cout<<A[i]<<" ";
}
}
归并排序
最新推荐文章于 2024-03-30 21:46:17 发布