您的位置:首页 > 编程语言 > PHP开发

PHP学习笔记【12】--PHP数组排序

2012-11-25 23:19 639 查看
<?php
//数组的排序
//排序分为内部排序和外部排序

//数据全部在内存中的排序叫内部排序

//数据量太大的话,无法全部加载到内存中,需要借助外部存储设备进行排序,叫做外部排序

//内部排序分类:1,冒泡排序2,快速排序3,选择排序;4,
$arr=array(3,1,5,7,3,123,54);
print_r($arr);
echo "<br/>";

//冒泡排序
function sortM(&$a){
$l=count($a);
for($x=1;$x<$l;$x++){
for($y=$x;$y<$l;$y++){
if($a[$y]<$a[$y-1]){
$temp=$a[$y];
$a[$y]=$a[$y-1];
$a[$y-1]=$temp;
}
}
}
}
//sortM($arr);

//选择排序
function selectSort(&$arr){
$l=count($arr);
for($v=0;$v<$l;$v++){
$minIndex=$v;
for($x=$v;$x<$l;$x++){
if($arr[$x]<$arr[$minIndex])$minIndex=$x;
}
$temp=$arr[$minIndex];
$arr[$minIndex]=$arr[$v];
$arr[$v]=$temp;
}
}
//selectSort($arr);

//插入排序
function insertSort(&$arr){

for($v=1;$v<count($arr);$v++){
//准备要插入的数据
$temp = $arr[$v];
$index=$v-1;
while($index>=0){
if($arr[$index]>$temp){
$arr[$index+1]=$arr[$index];
$index--;
}else{
$arr[$index+1]=$temp;
break;
}
}
if($index==-1)
$arr[0]=$temp;
}

}
insertSort($arr);

print_r($arr);

?>


本文出自 “Kenan_ITBlog” 博客,请务必保留此出处http://soukenan.blog.51cto.com/5130995/1070603
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: