php实现并归排序

<?php
/**
* Created by PhpStorm.
* User: KeenSting
* Date: 2017/12/7
* Time: 下午5:47
* Name: 梁小苍
* Phone: 13126734215
* QQ: 707719848
* File Description: 并归排序(分治与递归)
*/

//测试类
class ATest{
private $data; public function __construct($data)
{
$this->init($data);
}

//执行
public function run()
{
$this->merge(); print_r($this->data);
}
//初始化并归数组,相邻两个元素合并为一个数组
private function init($data) {$tmp = [];
$num = count($data);
if($num%2==0)$items = $num/2; else$items = ($num-1)/2; for($i=0;$i<$items;$i++) { if($data[2 * $i] <$data[2 * $i + 1]) array_push($tmp,[$data[2 *$i],$data[2 *$i + 1]]);
else
array_push($tmp,[$data[2 * $i + 1],$data[2 * $i]]); } if($num%2!=0)
array_push($tmp,[$data[$num-1]]);$this->data = $tmp; } //并归递归调用 private function merge() {$re = [];
$size = count($this->data);
if($size!=1)//没有完成并归,继续 { for($i=0;$i<$size-1;$i+=2)$re[] = $this->doubleMerge($this->data[$i],$this->data[$i+1]); if($size%2 != 0)
$re[] =$this->data[$size-1];$this->data = $re;$this->merge();
}
}

//合并两个有序序列
private function doubleMerge($a,$b)
{
$re = [];$i = $j = 0;$s1 = count($a);$s2 = count($b); while(true) { if($a[$i] <=$b[$j]) { array_push($re,$a[$i]);
$i++; }else { array_push($re,$b[$j]);
$j++; } if($i==$s1) return array_merge($re, array_slice($b,$j));

if($j==$s2)
return array_merge($re, array_slice($a, $i)); } } }$a = new ATest([3,1,9,2,7,6,11,5,4,13]);
\$a->run();


Array

(

[0] => Array

(

[0] => 1

[1] => 2

[2] => 3

[3] => 4

[4] => 5

[5] => 6

[6] => 7

[7] => 9

[8] => 11

[9] => 13

)

)

• 本文已收录于以下专栏：

举报原因： 您举报文章：php实现并归排序 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)