PHP implements two-way merge sort

WBOY
Release: 2016-07-29 08:51:31
Original
921 people have browsed it

 1$arr = [9, 43, 12, 0, 87, 1];
 2function merge_sort(&$arr){
 3     _merge_sort($arr, $arr, 0, count($arr) - 1);
 4}
 5 6function _merge_sort(&$s_arr, &$d_arr, $i, $j){
 7if($i > $j){
 8return;
 9    }
10if($i == $j){
11echo 'aa';
12$d_arr[$i] = $s_arr[$i];
13returnfalse;
14    }
15$tmp_arr = array();
16$m = intval(($i + $j)/2);
17echo$m;
18if($i <= $m){
19         _merge_sort($s_arr, $tmp_arr, $i, $m);
20    }
21if($m+1 <= $j ){
22         _merge_sort($s_arr, $tmp_arr, $m+1, $j);
23    }
24     merge($tmp_arr, $d_arr, $i, $m, $j);
25}
26 //$s_arr中的$start到$m与$m到$end两个序列都是有序的,将这两个序列合并到$d_arr里面
27function merge(&$s_arr, &$d_arr, $start, $m, $end){
28$i = $start; $j = $m+1;$d_i = $i;
29while($i <= $m && $j <= $end){
30if($s_arr[$i] > $s_arr[$j]){
31$d_arr[$d_i++] = $s_arr[$i++];
32//$i++;33         }else{
34$d_arr[$d_i++] = $s_arr[$j++];
35        }
36    }
37while($i <= $m){
38$d_arr[$d_i++] = $s_arr[$i++];
39//$i++;40    }
41while ($j <= $end) {
42$d_arr[$d_i++] = $s_arr[$j++];
43    }
44 }
Copy after login

The above introduces the implementation of two-way merge sorting in PHP, including the relevant aspects. I hope it will be helpful to friends who are interested in PHP tutorials.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!