PHP 归并算法-分而治之

<?php
$arr
= [5,12,3,55,3,9,10,3,23,123,4,9]; /** * [branch 分] * @param array $arr [description] * @return [type] [description] */ function branch( array $arr):array{ // 切割成粒度为1的数组返回 if(count($arr) == 1 ){ return $arr; } $s = intval(count($arr) /2); $left = array_slice($arr,0,$s); $right = array_slice($arr,$s); $left = branch($left); $right = branch($right); // left right两个数组进行排序合并 $arr = sortMerge($left,$right); return $arr; } /** * [sortMerge 治] * @param array $left [description] * @param array $right [description] * @return [type] [description] */ function sortMerge(array $left, array $right):array { $tmp = []; while(count($left) && count($right)){ $tmp[] = $left[0] > $right[0]?array_shift($right):array_shift($left); } echo '<pre>'; echo 'tmp->'; print_r($tmp); echo 'left->'; print_r($left); echo 'right->'; print_r($right); echo '<hr>'; echo '</pre>'; return array_merge($tmp,$left,$right); } $R = branch($arr); echo '<pre>'; print_r($R); echo '</pre>';

 

posted @ 2021-07-01 17:44  时间掉飞机  阅读(40)  评论(0编辑  收藏  举报