Yesterday said a quick sort, today speaking of merge sort :
What is merging?
Merge : Combine two or more two ordered tables into a new ordered table.
Steps for merging operations:
The space is applied to the sum of two sorted sequences, which are used to store the merged sequence
Set two pointers where the initial position is the starting position of the two sorted series
Compare the elements pointed to by two pointers, select a relatively small element into the merge space, and move the pointer to the next position
Repeat step 3 until a pointer exceeds the end of the sequence
Copies all remaining elements of another sequence directly to the end of the merge sequence
Merge plot:
Code implementation:
#include <iostream>using namespace STD;//combine array A[low,mid] with a (mid,high) (merge)voidMerge (intBintLowintMidintHighint* Temp) {intI,j,k; i = low; j = Mid +1;//Avoid repeating comparisons A[mid]K =0; while(I <= mid && J <= High)//array A[low,mid] and array (Mid,high] are not all grouped into the array temp{if(A[i] <= a[j])//If a[i] is less than or equal to A[j]temp[k++] = a[i++];//The value of A[i] will be assigned to Temp[k], and then i,k each plus one, which means to move back one Elsetemp[k++] = a[j++];///Otherwise, assign the value of A[j] to temp[k],j,k each plus one} while(I <= mid)//indicates that the array a (Mid,high] has all been grouped into the temp array, and the array A[low,mid] has the remainingtemp[k++] = a[i++];//A[low,mid The remaining values of the array into the array temp while(J <= High)//= array A[low,mid] has all been grouped into the temp array, and the array (Mid,high] has the remainingtemp[k++] = a[j++];//Put the remaining values of array a (Mid,high], grouped into the array temp for(i =0; I < K; i++)//Assign the values of the merged array to the array A[low,high]A[low+i] = Temp[i];//Note that the assignment should begin with A[low+i]}//Two-way merge (recursive implementation)voidMergeSort (intAintLowintHighint* Temp) {if(Low < High) {intMid = (low + high)/2; MergeSort (a,low,mid,temp);//Left orderMergeSort (a,mid+1, high,temp);//Right orderMerge (a,low,mid,high,temp);//Merge two sequential sequences}}/ *----------Test Code----------* /intMain () {intA[] = {2, at, the, +, $,6,7,8,5,4, About, +, the,211,222,444,111};intLa =sizeof(a)/sizeof(a[0]);int* p =New int[La]; MergeSort (A,0, la-1, p); for(inti =0; i < La; i++) {cout<<a[i]<<"'; }cout<<endl;Delete[]p;}
Test results:
Time Efficiency: O (NLOG2N)
Space Efficiency: O (N)
Stability: Stable
Data structure--merge sort algorithm