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

使用 php 进行冒泡排序

Jun 02, 2016 am 09:14 AM

跳至 [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
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)