一、排序
1、冒泡
//冒泡
$arr = array(2,4,654,76,43,23,65,786,43,12);
function mySort($arr){
for($i = 0;$i $arr[$j+1]){
$t = $arr[$j];
$arr[$j] = $arr[$j+1];
$arr[$j+1] = $t;
}
}
}
return $arr;
}
var_dump(mySort($arr));
2、快排
//快排
$arr = array(2,4,654,76,43,23,65,786,43,12);
function mySort($arr){
if(count($arr) <= 1){
return $arr;
}
$left = $right = array();
for($i = 1;$i $arr[0]){
$right[] = $arr[$i];
}else{
$left[] = $arr[$i];
}
}
$left = mySort($left);
$right = mySort($right);
return array_merge($left,array($arr[0]),$right);
}
var_dump(mySort($arr));
3、插入
//插入
//
$arr = array(2,4,654,76,43,23,65,786,43,12);
function mySort($arr){
for($i = 1;$i < count($arr);$i++){
for($j = $i;$j > 0;$j--){
if($arr[$j] < $arr[$j-1]){
$t = $arr[$j];
$arr[$j] = $arr[$j-1];
$arr[$j-1] = $t;
}else{
break;
}
}
}
return $arr;
}
var_dump(mySort($arr));
4、二维数组排序
//二维数组根据指定字段排序(asc)
$arr = array(
0=>array('id'=>8,'name'=>'Tom'),
1=>array('id'=>9,'name'=>'Peter'),
2=>array('id'=>5,'name'=>'Jack')
);
function mySort($arr,$sort_key,$sort_order=SORT_ASC,$sort_type=SORT_NUMERIC){
$arrs = array();
if(is_array($arr) || is_array($arrs)){
foreach($arr as $key => $value){
$arrs[] = $value[$sort_key];
}
array_multisort($arrs,$sort_order,$sort_type,$arr);
return $arr;
}
}
var_dump(mySort($arr,'id'));
二、查找
1、顺序(必须考虑效率)
//顺序查找
$arr = array(1,2,3,4,5,6,7,8,9,12,14,15,16);
function search($arr,$key){
$n = count($arr);
$arr[$n] = $key;
for($i = 0;$i < $n;$i++){
if($arr[$i] == $key){
break;
}
}
if($i < $n){
return $i;
}else{
return -1;
}
}
var_dump(search($arr,12));
2、二分
//二分查找
$arr = array(1,2,3,4,5,6,7,8,9,12,14,15,16);
$low = 0;
$high = count($arr)-1;
$key = 12;
function search($arr,$low,$high,$key){
while($low <= $high){
$mid = intval(($low+$high)/2);
if($arr[$mid] == $key){
return $mid;
}elseif($arr[$mid] < $key){
$low = $mid +1;
}elseif($arr[$mid] > $key){
$high = $mid -1;
}
}
return -1;
}
var_dump(search($arr,$low,$high,$key));