#include<iostream> #include<malloc.h> using namespace std; void Merge(int a[], int low , int mid, int high){ int i = low; int j = mid+1; int k = 0; int *temp = (int *)malloc((high -low +3) *sizeof(int)); while(i<=mid && j<=high){ if(a[i] < a[j]){ temp[k++]= a[i]; } if(a[j] < a[i]){ temp[k++] = a[j++]; } } while(i<=mid){ temp[k++]= a[i++]; } while(j<=high){ temp[k++]= a[j++]; } for(int i=low, k = 0; i<=high; i++, k++){ a[i]=temp[k]; } free(temp); } void MergeSort(int a[], int low, int high){ if(low < high){ int mid = (low + high)/2; MergeSort(a, low, mid); MergeSort(a, mid+1, high); Merge(a,low, mid, high); } } void show(int a[], int n) { cout<<a[0]; for(int i=1; i<n; i++) { cout<<" ,"<<a[i]; } } int main() { int a[10]= {9,8,7,6,5,4,3,2,1}; cout<<"排序前:"; show(a, 9); cout<<endl; MergeSort(a,0,8); cout<<"排序后:"; show(a, 9); }