Home > Backend Development > PHP Tutorial > PHP兑现常见排序算法

PHP兑现常见排序算法

WBOY
Release: 2016-06-13 13:24:52
Original
1115 people have browsed it

PHP实现常见排序算法


//插入排序(一维数组)
function insert_sort($arr){
?$count = count($arr);
?for($i=1; $i?$tmp = $arr[$i];
?$j = $i - 1;
?while($arr[$j] > $tmp){
?$arr[$j+1] = $arr[$j];
?$arr[$j] = $tmp;
?$j--;
?}
?}
?return $arr;
}
//选择排序(一维数组)
function select_sort($arr){
?$count = count($arr);
?for($i=0; $i?$k = $i;
?for($j=$i+1; $j?if ($arr[$k] > $arr[$j])
?$k = $j;
?if ($k != $i){
?$tmp = $arr[$i];
?$arr[$i] = $arr[$k];
?$arr[$k] = $tmp;
?}
?}
?}
?return $arr;
}
//冒泡排序(一维数组)
function bubble_sort($array){
?$count = count($array);
?if ($count ?
?for($i=0; $i?for($j=$count-1; $j>$i; $j--){
?if ($array[$j] ?$tmp = $array[$j];
?$array[$j] = $array[$j-1];
?$array[$j-1] = $tmp;
?}
?}
?}
?return $array;
}
//快速排序(一维数组)
function quick_sort($array){
?if (count($array)

?$key = $array[0];
?$left_arr = array();
?$right_arr = array();
?for ($i=1; $i?if ($array[$i] ?$left_arr[] = $array[$i];
?else
?$right_arr[] = $array[$i];
?}
?$left_arr = quick_sort($left_arr);
?$right_arr = quick_sort($right_arr);
?
?return array_merge($left_arr, array($key), $right_arr);

}
?>

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template