function InsertSort($arr){ $num = count($arr); for($i = 1; $i < $num; $i++){ $key = $arr[$i]; for($j = $i - 1; $j >= 0; $j--){ if($arr[$j] > $key){ $arr[$j + 1] = $arr[$j]; $arr[$j] = $key; } } } return $arr; } function BubbleSort($arr){ $num = count($arr); for( $i = 1; $i < $num; $i++ ){ for($j = $num -1; $j >= $i; $j-- ){ if( $arr[$j] < $arr[$j - 1] ){ $tmp_val = $arr[$j - 1]; $arr[$j - 1] = $arr[$j]; $arr[$j] = $tmp_val; } } } return $arr; } function BucketSort($arr){ $bucket = array(); $idx = 0; foreach ($arr as $value) { if(!is_int($value)) continue; $bucket[$value] = $value; if($value > $idx) $idx = $value; } $rst = array(); for($i = 0; $i <= $idx; $i++){ if(isset($bucket[$i])){ $rst[] = $bucket[$i]; } } return $rst; } function ExchangeSort($arr){ $num = count($arr); for($i = 0; $i < $num -1; $i++){ for($j = $i + 1; $j < $num; $j++){ if($arr[$i] > $arr[$j]){ $tmp = $arr[$i]; $arr[$i] = $arr[$j]; $arr[$j] = $tmp; } } } return $arr; } function QuickSort($arr){ $num = count($arr); $l_num = $r_num = 0; $left = $right = array(); for($i = 1; $i < $num; $i++){ if($arr[$i] >= $arr[0]){ $right[] = $arr[$i]; $r_num++; }else{ $left[] = $arr[$i]; $l_num++; } } if($l_num > 1){ $left = QuickSort($left); } $left[] = $arr[0]; if($r_num > 1){ $right = QuickSort($right); } for($i = 0; $i < $r_num; $i++){ $left[] = $right[$i]; } return $left; } function PigeonholeSort($arr){ $pigeonhole = array(); foreach ($arr as $value) { if(!is_int($value)) continue; if(isset($pigeonhole[$value])) $pigeonhole[$value]++; else $pigeonhole[$value] = 0; } $rst = array(); $i = 0; while($pigeonhole[$i]){ for($j = 0; $j < $pigeonhole[$i]; $j++){ $rst[] = $i; } $i++; } return $rst; }
原文:http://www.cnblogs.com/zhaobolu/p/3781844.html