algorithm design
(1) Decomposition---The elements to be sorted are divided into two subsequences of roughly the same size. (2) Governance --- Merge sort the two subsequences. (3) Merge --- Merge the sorted ordered subsequences to obtain the final ordered sequence.
Detailed Pseudocode
(1) Merge operation
int *B=new int[high-low+1]; int i=low,j=mid+1,k=0; while(i<=mid&&j<=high) { if(A[i]<=A[j]) B[K++]=A[i++] else B[K++]=A[j++]; }
( 2 ) Merge sort algorithm in recursive form
void MergeSort(int A[],int low,mid,int high) { if(low<=high){ int mid=(low+high)/2; MergeSort(A,low,mid); MergeSort(A,mid+1,high); Merge(A,low,mid,high);//Merge algorithm } }
Detailed code
#include<iostream> #include<cstdio> #include<cstdlib> using namespace std; void Merge(int A[],int low,int mid,int high){ int *B=new int[high-low+1]; int i=low,j=mid+1,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(i=low,K=0;i<=high;i++) A[i]=B[K++]; delete []B; } 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);//Merge algorithm } } int main() { int n,A[100]; cout<<"Please enter the number n of elements in the sequence: "<<endl; cin>>n; cout<<"Please enter the elements in the sequence in sequence:"<<endl; for(int i=0;i<n;i++) cin>>A[i]; MergeSort(A,0,n-1); cout<<"Merge sort result:"<<endl; for(int i=0;i<n;i++) cout<<A[i]<<" "; cout<<endl; return 0; }