#include <iostream>
using namespace std;
template <class Type>
void swap(Type* A, int i, int j){
Type temp = A[i];
A[i] = A[j];
A[j] = temp;
}
template <class Type>
void Merge(Type* A,Type* Temp, int left,int right,int middle){
for(int i = left; i<= right; i++) Temp[i] = A[i];
int index1 = left,index2 = middle + 1;
int i = left;
while(index1 <= middle && index2 <= right){
if(Temp[index1] <= Temp[index2])
A[i++] = Temp[index1++];
else A[i++] = Temp[index2++];
}
while(index1 <= middle) A[i++] = Temp[index1++];
while(index2 <= right) A[i++] = Temp[index2++];
}
template <class Type>
void MergeSort(Type* A,Type* Temp, int left,int right){
if(left == right) return;
int middle = (left + right)/2;
MergeSort(A,Temp,left,middle);
MergeSort(A,Temp,middle+1,right);
Merge(A,Temp,left,right,middle);
}
int a[100];
int temp[100];
int main(){
int n;
cin >> n;
for(int i = 0; i < n;i++)
cin >> a[i];
MergeSort(a,temp,0,n-1);
for(int i = 0; i < n;i++)
cout<< a[i] << " ";
cout<<endl;
return 0;
}
【排序算法】归并排序
最新推荐文章于 2024-08-12 19:32:44 发布