# 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实现排序算法----归并排序（Merging Sort）

2016-11-27 13:47:14

#### Java语言 实现并归排序

2016-03-01 16:09:51

#### PHP实现归并排序（合并排序）--算法原理分析

2015-10-18 17:56:25

#### php实现归并排序

2016-01-17 22:33:13

#### （高效率排序算法一）并归排序

2015-04-30 16:24:02

#### Java语言实现各种排序算法

2017-05-21 15:28:11

#### Java语言实现的各种排序

2007-05-16 08:10:00

#### 排序(6)---------归并排序(C语言实现)

2014-06-29 23:25:36

#### java之并归排序

2016-11-10 19:47:32

#### 外排序的C++实现（归并时利用败者树）

2016-11-02 20:52:49