解读PHP冒泡排序技巧


PHP语言与C语言有些相向。但只是相向,并不代表相同。我们在这篇文章中将会为大家详细介绍有关PHP冒泡排序的一些使用方法。

PHP冒泡排序程序文件sort_bubble_up.php
 

< html> 
< head>< title>PHP冒泡排序法演示< /title>< head> 
< link rel="stylesheet" href="sort.css"> 
< body> 
< h1>冒泡排序法演示< /h1> 
< table cellpadding="5" cellspacing="1"
border="0" align="center"> 
< ?php  
//随机生成数组  
$arr=array();  
echo '< tr>< td colspan="10" class="title">
初始值< /td>< /tr>';  
echo '< tr>';  
for($i=0;$i< 10;$i++){  
$arr[$i]=rand();  
echo "< td>\$arr[$i]={$arr[$i]}< /td>";  
}  
//进行冒泡法排序  
for($i=9;$i>0;$i--){  
echo '< tr>< td colspan="10" class="title">第'
.(10-$i).'次< /td>< /tr>';  
for($j=0;$j< $i;$j++){  
if($arr[$j]< $arr[$j+1]){  
$tmp=$arr[$j];  
$arr[$j]=$arr[$j+1];  
$arr[$j+1]=$tmp;  
}   
echo '< tr>';  
for($k=0;$k< 10;$k++){  
switch($k){   
case $j : echo '< td class="base">'; break;  
case $j+1 : echo '< td class="light">'; break;  
default : echo '< td>';  
}  
echo "\$arr[$k]={$arr[$k]}< /td>";  
}  
echo '< /tr>';  
}  
}  
//显示排序结果  
echo '< tr>< td colspan="10" class="title">结果< /td>< /tr>';  
echo '< tr>';  
for($i=0;$i< 10;$i++){  
echo "< td>\$arr[$i]={$arr[$i]}< /td>";  
}  
echo '< /tr>';  
?> 
< /table> 
< /body>< /html> 
PHP冒泡排序样式表文件sort.css

h1{text-align: center; color: blue;}
table{font-size: 12px; font-family: arial; background-color: black; text-align: center;}
td{background-color: white;}
.base{background-color: #0FF;}
.light{background-color: #0DD;}
.title{background-color: #3FF; text-align: center;}


« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3