There are many kinds of PHP sorting algorithm, this article is mainly for you to introduce the PHP sorting algorithm series of the merger sort of related data, with a certain reference value, interested in small partners can refer to, hope to help everyone.
Merge sort
Merge sort (Merge-sort) is an efficient sorting algorithm based on merging operation, which is a very typical application of divide-and-conquer method (Pide 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.
Merge process
The core of the merge sort is how to merge two ordered sequences, assuming there are two ordered arrays, comparing the first element of two ordered arrays, who takes the small one, and puts the element in the third array, takes the element in the corresponding array, and so on, and so on, when taking an array that has no elements, You can add the remaining elements of another array directly to the third array.
Principle
1, the sequence of each adjacent two numbers are merged to form a ceil (N/2) sequence, sorted after each sequence contains two elements, the last sequence may have only one element.
2, the above sequence is merged again, form Ceil (N/4) sequence, each sequence contains four elements, the last sequence may have only three and the following elements.
3. Repeat step 2 until all the elements have been sorted.
Example
Sorting an array [53,89,12,6,98,25,37,92,5]
After the first merge
(53,89), 12, (6,98), (25,37), (5,92)
After the second merge
(12,53,89), (6,25,37,98), (5,92)
After the third merge
(6,12,25,37,53,89,98), (5,92)
After the fourth time merge
5,6,12,25,37,53,89,92,98
PHP Code implementation
<?phpfunction Merge_sort ($arr) { $length =count ($arr); if ($length <=1) { return $arr; } Decompose arrays, recursively sort $half =ceil ($length/2); $arr 2=array_chunk ($arr, $half); $left =merge_sort ($arr 2[0]); $right =merge_sort ($arr 2[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);}
Have you learned it? Let's try it out for a moment.