PHP 歸併演算法-分而治之
阿新 • • 發佈:2021-07-01
<?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>';