标签:
归并排序,是将子序列进行两两合并,最后并为一个有序序列。
#include <iostream> #include <cstring> #include <cstdlib> using namespace std; #define maxn 20 void Merge(int a[],int low,int mid,int high) { int i=low; int j=mid+1; int b[maxn]; int k=0; while(i<=mid&&j<=high) { if(a[i]<=a[j]) b[k++]=a[i++]; else b[k++]=a[j++]; } while(i<=mid) b[k++]=a[i++]; while(j<=high) b[k++]=a[j++]; for(int m=low,n=0; m<=high; m++,n++) a[m] = b[n]; } void MSort(int a[],int low,int high) { int mid; if(low<high) { mid = (low + high)/2 ; MSort(a,low,mid); MSort(a,mid+1,high); Merge(a,low,mid,high); } } int main() { int n; int a[maxn]={0}; cin>>n; for(int i=0; i<n; i++) cin>>a[i]; MSort(a,0,n-1); for(int i=0; i<n; i++) cout<<a[i]<<" "; return 0; }
标签:
原文地址:http://blog.csdn.net/tingyu1995/article/details/46593693