代码:
#include<iostream>
using namespace std;
class List{
public:
List(){
array=NULL;
}
void creat(){
int n;
cout<<"请输入数组大小:";
cin>>n;
this->n=n;
array=new int[n];
for(int i=0;i<n;i++){
cin>>array[i];
}
}
void print(){
for(int i=0;i<n;i++){
cout<<array[i]<<" ";
}
cout<<endl;
}
void sort(){
sort(0,n-1);
}
private:
void merge(int lo,int hi){
int mid=(lo+hi)/2;
int n1=mid-lo+1;
int n2=hi-mid;
int *a1=new int[n1];
int *a2=new int[n2];
int k=lo;
for(int i=0;i<n1;i++){
a1[i]=array[k++];
}
for(int i=0;i<n2;i++){
a2[i]=array[k++];
}
int i=0;
int j=0;
k=lo;
while(i<n1&&j<n2){
if(a1[i]<=a2[j]){
array[k++]=a1[i++];
}
else{
array[k++]=a2[j++];
}
}
while(i<n1){
array[k++]=a1[i++];
}
while(j<n2){
array[k++]=a2[j++];
}
print();
}
void sort(int lo,int hi){
if(lo<hi){
int mid=(lo+hi)/2;
sort(lo,mid);
sort(mid+1,hi);
merge(lo,hi);
}
}
int *array;
int n;
};
int main(){
List l;
l.creat();
l.sort();
l.print();
}