Home  >  Article  >  php教程  >  php 数组排序:php实现各种排序

php 数组排序:php实现各种排序

WBOY
WBOYOriginal
2016-06-21 08:51:33942browse

/**
* 各种排序
* @author zhaojaingwei
* @since 2011/11/21 16:14
*
*/
$list = array(3,5,1,2,10,8,15,19,20);
//快排
function fast(&$list, $low, $high){
if($high - $low > 5){
while($low $key = excute($list, $low, $high);
fast($list, $low, $key - 1);
//fast($list, $key + 1, $high);//普通递归实现
$low = $key + 1;//尾递归实现
}
}else{
insert($list);
}
}
//快排执行一次排序
function excute(&$list, $low, $high){
swap($list, $low, ($low + $high)/2);
$temp = $list[$low];
while($low while($low $temp){
$high --;
}
$list[$low] = $list[$high];
while($low $low ++;
}
$list[$high] = $list[$low];
}
$list[$low] = $temp;
return $low;
}
//堆排序
function heap(&$list){
buildheap($list);
for($i = count($list) - 1; $i > 0; $i --){
swap($list, $i, 0);
heapfy($list, 0, $i - 1);
}
}
//创建堆
function buildheap(&$list){
for($i = (count($list) - 2)/2; $i >= 0; $i --){
heapfy($list, $i, count($list) - 1);
}
}
//维护堆
function heapfy(&$list, $low, $high){
$temp = $list[$low];
for($i = ($low * 2 + 1); $i if($i $i ++;
}
if($temp swap($list, $i, $low);
$low = $i;
}else{
break;
}
}
$list[$low] = $temp;
}
//希尔排序
function shell(&$list){
$a = 0;
$code = count($list)/3 + 1;
while($code >= 1){
for($i = $code; $i $a ++;
if($list[$i] $temp = $list[$i];
$list[$i] = $list[$i - $code];
$j = $i - 2*$code;
for(; $j >= 0 && $list[$j] > $temp; $j -= $code){
$list[$j + $code] = $list[$j];
$a ++;
}
$list[$j + $code] = $temp;
}
}
$code = $code/3;
}
echo $a;
}
//直接插入排序
function insert(&$list){
$a = 0;
for($i = 1; $i $a ++;
if($list[$i] $temp = $list[$i];
$list[$i] = $list[$i - 1];
$j = $i - 2;
for(; $list[$j] > $temp; $j --){
$a ++;
$list[$j + 1] = $list[$j];
}
$list[$j + 1] = $temp;
}
}
echo $a;
}
//简单选择排序
function select(&$list){
$a = 0;
for($i = 0; $i $min = $i;
$a ++;
for($j = $i + 1; $j $a ++;
if($list[$j] $min = $j;
}
}
if($min != $i)
swap($list, $i, $min);
}
echo $a;
}
//冒泡排序
function bubble(&$list){
$swap = true;
$a = 0;
for($i = 0; $i $swap = false;
$a ++;
for($j = count($list) - 2; $j >= $i; $j --){
$a ++;
if($list[$j] > $list[$j + 1]){
$swap = true;
swap($list, $j, $j + 1);
}
}
}
echo $a;
}
//移动或交换函数
function swap(&$list, $i, $j){
$temp = $list[$i];
$list[$i] = $list[$j];
$list[$j] = $temp;
}
?> 本文链接http://www.cxybl.com/html/wlbc/Php/20120607/28506.html



Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn