Merge sort (also called merge sort) is a sorting algorithm based on O (n log n) comparison. Most implementations produce a stable sort, which means that the implementation preserves the input order of equal elements in the sorted output.
Now we will introduce to you how to use PHP to implement the merge sort algorithm.
PHP code example is as follows:
<?php function merge_sort($my_array){ if(count($my_array) == 1 ) return $my_array; $mid = count($my_array) / 2; $left = array_slice($my_array, 0, $mid); $right = array_slice($my_array, $mid); $left = merge_sort($left); $right = merge_sort($right); return merge($left, $right); } function merge($left, $right){ $res = array(); while (count($left) > 0 && count($right) > 0){ if($left[0] > $right[0]){ $res[] = $right[0]; $right = array_slice($right , 1); }else{ $res[] = $left[0]; $left = array_slice($left, 1); } } while (count($left) > 0){ $res[] = $left[0]; $left = array_slice($left, 1); } while (count($right) > 0){ $res[] = $right[0]; $right = array_slice($right, 1); } return $res; } $test_array = array(100, 54, 7, 2, 5, 4, 1); echo "原始数组 : "; echo implode(', ',$test_array ); echo "\n排序后数组:"; echo implode(', ',merge_sort($test_array))."\n";
Output:
原始数组 : 100, 54, 7, 2, 5, 4, 1 排序后数组:1, 2, 4, 5, 7, 54, 100
Related function introduction:
array_slice() Function in array Take a value based on the condition and return it.
array_slice ( array $array , int $offset [, int $length = NULL [, bool $preserve_keys = FALSE ]] ) : array
array_slice() returns a sequence in the array array specified by the offset and length parameters.
implode()The function converts the value of a one-dimensional array into a string.
Related recommendations: "PHP Tutorial"
This article is an introduction to the method of implementing the merge sort algorithm in PHP. I hope it will be helpful to friends in need!
The above is the detailed content of PHP implements merge sort algorithm (code example). For more information, please follow other related articles on the PHP Chinese website!