PHP sort algorithm series merge sort details, sort algorithm merge details
Merge Sorting
MERGE-SORT is an effective Sorting Algorithm Based on MERGE operations. It is a typical application of Divide and Conquer. Merges ordered subsequences to obtain a fully ordered sequence. That is, first orders each subsequence, and then orders the subsequence segments. If two ordered tables are merged into an ordered table, it is called a two-way merge.
Merge Process
The core of merging and sorting is how to merge two ordered sequences. Assume that there are two ordered arrays and the first element of the two ordered arrays is compared, add the element to the third array. After this element is obtained, it will be deleted in the corresponding array, and so on. When an array has no elements, you can add the remaining elements of another array to the third array.
Principle
1. merge each adjacent number to form a ceil (n/2) sequence. After sorting, each sequence contains two elements, and the last sequence may have only one element.
2. Merge the above sequence to form a ceil (n/4) sequence. Each sequence contains four elements. The last sequence may have only three or the following elements.
3. Repeat Step 2 until all elements are sorted.
Example
Sort arrays [,]
After the first merge
(), 12)
After the second merge
(, 89)
After the third merge
(6, 12, 25, 37, 53,89, 98), (5, 92)
After the fourth merge
, 98
PHP code implementation
<? Phpfunction merge_sort ($ arr) {$ length = count ($ arr); if ($ length <= 1) {return $ arr;} // breaks down the array, recursive sorting $ half = ceil ($ length/2); $ arr2 = array_chunk ($ arr, $ half); $ left = merge_sort ($ arr2 [0]); $ right = merge_sort ($ arr2 [1]); while (count ($ left) & count ($ right )) {if ($ left [0] <$ right [0]) {$ reg [] = array_shift ($ left );} else {$ reg [] = array_shift ($ right) ;}} return array_merge ($ reg, $ left, $ right );}
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.