php中的冒泡排序,取舍排序,插入排序

WBOY
Release: 2016-06-13 11:03:26
Original
699 people have browsed it

php中的冒泡排序,选择排序,插入排序


??//冒泡排序
??function bubbleSort(&$arr){
????
????$temp=0;
????
????//加入第i个数最大
????for($i=0;$i??????
??????for($j=0;$j??????
????????//说明前面的数比后面的数大,就要交换
????????if($arr[$j] > $arr[$j+1]){
??????????$temp=$arr[$j];
??????????$arr[$j]=$arr[$j+1];
??????????$arr[$j+1]=$temp;
????????}
??????}
??????
????
????}
??}
??
??//选择排序
??function selectSort(&$arr){
????
????$temp=0;
????
????for($i=0;$i?????
??????//假设$i就是最小的数
??????$minValue=$arr[$i];
??????//记录我认为最小数的下标
??????$minIndex=$i;
??????
??????for($j=$i+1;$j????????
????????//我们认为的最小值,不是最小
????????if($minValue>$arr[$j]){
??????????
??????????$minValue=$arr[$j];
??????????$minIndex=$j;
??????????
????????}
??????}
??????
??????//最后交换
??????$temp=$arr[$i];
??????$arr[$i]=$arr[$minIndex];
??????$arr[$minIndex]=$temp;
????}
??}
??
??//插入排序法
??function insertSort(&$arr){
????
????for($i=1;$i??????
??????//$insertVal是准备插入的数
??????$insertValue=$arr[$i];
??????//准备先和$insertIndex比较
??????$insertIndex=$i-1;
??????
??????//如果这个条件满足,说明,我们还没有找到适当的位置
??????while($insertIndex>=0 && $insertValue ??????
????????//同时把数后移
????????$arr[$insertIndex+1]=$arr[$insertIndex];
????????
????????$insertIndex--;
??????}
??????
??????//插入(这时给$insertValue找到适合位置)
??????$arr[$insertIndex+1]=$insertValue;
????}
??}

??$arr = Array(0,-1,5);
??
??//冒泡排序法
??//bubbleSort($arr);
??//选择排序法
??//selectSort($arr);
??//插入排序法
??insertSort($arr);
??print_r($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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!