1. Basic Ideas
Merge sort is an effective sorting algorithm based on merging operation, which is a very typical application of the partition method (Divide and Conquer). The ordered Subsequence is merged to obtain a fully ordered sequence, i.e., the order of each subsequence is ordered, and then the sequence of sub-sequences is ordered. If two ordered tables are combined into an ordered table, they are called two-way merging.
2. Principle of Implementation
Recursively divides the array into two sub-arrays, always recursively to only one element in the array, and then calls the function to order the two sub-arrays, because the function is pushed into the stack when recursively dividing the array, so the function is to sort the two ordered sub-arrays in a real order;
3. Code Examples
(1) Code:
Public Static voidMergeint[] arr,intFirstintMidintLastint[] sorted) { inti = First, j =mid; intK = 0; while(I < mid && J <Last )if(Arr[i] <Arr[j]) sorted[k+ +] = arr[i++]; Elsesorted[k+ +] = arr[j++]; while(I <mid) Sorted[k+ +] = arr[i++]; while(J <Last ) Sorted[k+ +] = arr[j++]; for(intv = 0; v < K; v++) Arr[first+ V] =sorted[v];} Public Static voidMerge_sort (int[] unsorted,intFirstintLastint[] sorted) { if(First + 1 <Last ) { intMid = (first + last)/2; Merge_sort (unsorted, first, Mid, sorted);//Left OrderMerge_sort (unsorted, Mid, last, sorted);//Right Ordermerge (unsorted, first, mid, last, sorted);//two numeric merges }} Public Static voidMain (string[] args) {int[] Array = {6, 2, 4, 1, 5, 9};//Original Array int[] sorted =New int[Array.Length];//new array, sorted valuesmerge_sort (Array,0, Array.Length, sorted); for(intnum:sorted) {System.out.print (num+ " "); }}
(2) Results:
1 2 4 5 6 9
4. Algorithm analysis
The efficiency of the merge sort is relatively high, set the sequence length is N, divide the series into small series to Logn step, each step is a process of merging ordered series, the time complexity can be recorded as O (N), so altogether O (Nlogn). Because the merge sort is done in the adjacent data each time, several sorting methods (quick sorting, merge sort, hill sort, heap sort) of the merge sort in O (Nlogn) are also relatively efficient.
5. Sorting features
Sorting algorithm (8)--merge sorting--merge sort--merge sort--merge sort