Home > php教程 > PHP源码 > 使用 php 进行冒泡排序

使用 php 进行冒泡排序

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-06-02 09:14:18
Original
1049 people have browsed it
跳至 [1] [全屏预览]
<meta charset="gb2312" />
<?PHP
    //数组元素值从小到大排序
    $arr=array(1,42,0,3,15,7,19,26);
	foreach($arr as $k=>$v)
	echo " index:$k -- value:$v<br>";
	
    echo "<hr color=red />";
	echo "After applying sort() <br>";	
	$ar=$arr;
    //定义一个中间变量
	sort($ar);
   	print_r($ar); 
	
	echo '<br><hr color=red />';
  	echo "使用 冒泡排序";
    $temp=0;
    //外层循环的次数
    for($i=0;$i<count($arr)-1;$i++){
		$exchange=false;
        //内层之间向右相邻的两个数组元素值进行比较
        for($j=0;$j<count($arr)-1-$i;$j++){
            //当后一个数组元素值大于前一个数组原数值
            if($arr[$j]>$arr[$j+1]){
            //数组元素交换
               $temp=$arr[$j];
               $arr[$j]=$arr[$j+1];
               $arr[$j+1]=$temp;
			   $exchange=true;
              }

           }
        //外层数组循环的次数是---count($arr)-1
        //-1的原因(数组元素值比较时是两个比较
        //如3个数组元素比较2次
        echo "这是第".($i+1)."次比较的结果";
        echo "<pre/>";
        print_r($arr);
        echo "<pre/>";
		if (!$exchange) 
		break;
       }
    echo "<hr color=red />";
    echo "<pre/>";
    print_r($arr);
    echo "<pre/>"

?>
Copy after login
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 Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template