PHP 冒泡排序 二分查找 顺序查找 二维数组排序算法函数的详解_php技巧

WBOY
Release: 2016-05-17 08:58:49
Original
1049 people have browsed it

数据结构很重要,算法+数据结构+文档=程序
使用PHP描述冒泡排序算法,对象可以是一个数组

复制代码 代码如下:

//冒泡排序(数组排序)
function bubble_sort($array) {
$count = count($array);
if ($count return false;
for($i=0; $ifor($j=$count-1; $j>$i; $j–){
if ($array[$j] $tmp = $array[$j];
$array[$j] = $array[$j-1];
$array[$j-1] = $tmp;
}
}
}
return $array; }

使用PHP描述顺序查找和二分查找(也叫做折半查找)算法,顺序查找必须考虑效率,对象可以是一个有序数组
复制代码 代码如下:

//二分查找(数组里查找某个元素)
function bin_sch($array, $low, $high, $k){
if ($low $mid = intval(($low+$high)/2);
if ($array[$mid] == $k){
return $mid;
}elseif ($k return bin_sch($array, $low, $mid-1, $k);
}else{
return bin_sch($array, $mid+1, $high, $k);
}
}
return -1;
}
//顺序查找(数组里查找某个元素)
function seq_sch($array, $n, $k){
$array[$n] = $k;
for($i=0; $iif($array[$i]==$k){
break;
}
}
if ($ireturn $i;
}else{
return -1;
}
}

写一个二维数组排序算法函数,能够具有通用性,可以调用php内置函数
复制代码 代码如下:

//二维数组排序, $arr是数据,$keys是排序的健值,$order是排序规则,1是升序,0是降序
function array_sort($arr, $keys, $order=0) {
if (!is_array($arr)) {
return false;
}
$keysvalue = array();
foreach($arr as $key => $val) {
$keysvalue[$key] = $val[$keys];
}
if($order == 0){
asort($keysvalue);
}else {
arsort($keysvalue);
}
reset($keysvalue);
foreach($keysvalue as $key => $vals) {
$keysort[$key] = $key;
}
$new_array = array();
foreach($keysort as $key => $val) {
$new_array[$key] = $arr[$val];
}
return $new_array;
}

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