Home >php教程 >php手册 >php不用内置函数对数组排序的两个算法代码

php不用内置函数对数组排序的两个算法代码

WBOY
WBOYOriginal
2016-06-06 20:32:531678browse

php不用内置函数对数组排序,可能是降序或者升序

一朋友找工作遇到的试题,备注一下。
极有可能今后我也会遇到的。
问题:php不用内置函数对数组排序,可能是降序或者升序
第一种方法:传说中的冒泡法
代码如下:
function arraysort($data, $order = 'asc') {
//asc升序 desc降序
$temp = array ();
$count = count ( $data );
if ($count return false; //传入的数据不正确
if ($order == 'asc') {
for($i = 0; $i for($j = $count - 1; $j > $i; $j --) {
if ($data [$j] //交换两个数据的位置
$temp = $data [$j];
$data [$j] = $data [$j - 1];
$data [$j - 1] = $temp;
}
}
}
} else {
for($i = 0; $i for($j = $count - 1; $j > $i; $j --) {
if ($data [$j] > $data [$j - 1]) {
$temp = $data [$j];
$data [$j] = $data [$j - 1];
$data [$j - 1] = $temp;
}
}
}
}
return $data;
}
$data = array (7, 5, 3, 8, 9, 1, 5, 3, 1, 24, 3, 87, 0, 33, 1, 12, 34, 54, 66, 32 );
var_dump ( arraysort ( $data ) ); //升序
echo ('
');
var_dump ( arraysort ( $data ,'desc') );//降序

第二种方法:不知道取个什么名字好,就叫插入法吧!囧
代码如下:
function arraysort3($data, $order = 'asc') {
//目前只做升序排列
$count = count ( $data );
for($i = 1; $i $temp = $data [$i];
$j = $i - 1;
while ( $data [$j] > $temp ) {
$data [$j + 1] = $data [$j];
$data [$j] = $temp;
$j --;//为什么要递减:从高位逐位判断
}
}
return $data;
}
$data = array (7, 5, 3, 8, 9, 1, 5, 3, 1, 24, 3, 87, 0, 33, 1, 12, 34, 54, 66, 32 );
var_dump ( arraysort3 ( $data ) ); //升序
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