forked from m9rco/algorithm-php
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQuickSort.php
More file actions
34 lines (32 loc) · 1.15 KB
/
QuickSort.php
File metadata and controls
34 lines (32 loc) · 1.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<?php
/**
* @example 快速排序
* @author ShaoWei Pu <[email protected]>
* @date 2017/6/17
* @license Mozilla
* -------------------------------------------------------------
* 思路分析:从数列中挑出一个元素,称为 “基准”(pivot)
* -------------------------------------------------------------
* 重新排序数列,所有元素比基准值小的摆放在基准前面
* 所有元素比基准值大的摆在基准的后面(相同的数可以到任一边)。
* 递归地(recursive)把小于基准值元素的子数列和大于基准值元素的子数列排序
*/
/**
* @param array $container
* @return array|void
*/
function QulickSort( array $container ){
$count = count( $container );
if( $count <= 1 ) return;
$left = $right = [];
for ( $i =0; $i<$count-1;$i++ ){
if( $container[$i] < $container[0] ){
$left[] = $container[$i];
}else{
$right[]= $container[$i];
}
}
$left = QulickSort($left); $right = QulickSort($right);
return array_merge($left,[$container[0],$right]);
}
var_dump( QulickSort([4,21,41,2,53,1,213,31,21,423]) );