1. Concept
Merge sort is an efficient sorting algorithm based on the merge operation, which is a typical application of divide and conquer. Merge the ordered subsequences to obtain a completely ordered sequence, that is, order each subsequence first, and then order the subsequences. If two sorted lists are merged into one sorted list, it is called two-way merge.
2. Diagram
As shown in the figure, from bottom to top, each step needs to merge two already ordered subsequences into a large ordered array
3. Code implementation
//Merge two sorted arrays function merge(&$arr, $low, $mid, $high){ $temp = $arr; //Generate a temporary array, exactly the same as the original array, for later comparison $i = $low; $j = $mid+1; while ($low<=$mid && $j<=$high) { if ($temp[$low]>$temp[$j]) { $arr[$i++] = $temp[$j++]; }else { $arr[$i++] = $temp[$low++]; } } //if one of the arrays is left while ($low<=$mid) { $arr[$i++] = $temp[$low++]; } // the case where another array is left while ($j<=$high) { $arr[$i++] = $temp[$j++]; } unset($temp); // release the temporary array } //recursive call function merge_sort(&$arr,$low,$high) { if ($low>=$high) return; //end condition $mid = (int)(($low+$high)/2); merge_sort($arr,$low,$mid); merge_sort($arr,$mid+1,$high); merge($arr,$low,$mid,$high); } $arr = [12,56,98,32,16,34,2,9,1]; $len = count($arr); merge_sort($arr, 0, $len-1); dump($arr);
4. Effect display
5. Complexity Analysis
The time complexity of merge sort is O(nlogn) and the space complexity is O(n). But it is a stable sorting algorithm, because of the pairwise merge, they are based on the comparison between adjacent elements.