Home > php教程 > php手册 > body text

PHP冒泡排序算法实例详解

WBOY
Release: 2016-06-13 09:46:58
Original
1178 people have browsed it

在学校时我们老师告诉我们程序数据排序会有很多算法,其实冒泡算法是我们常用的一种排序算法了,下面我来用php实现冒泡排序,下面记录一下。

例1

 代码如下 复制代码

/**
 * 冒泡排序 (一维数组)
 * 两两比较待排序数据元素的大小,发现两个数据元素的次序相反时即进行交换,直到没有反序的数据元素为止
 * 设想被排序的数组R[1..N] 垂直竖立,将每个数据元素看作有重量的气泡,从下往上扫描数组,凡扫描违反原则的轻气泡,就使其向上"漂浮".如此反复进行.
 * 直到最后任何两个气都是轻者在上,重者在下为止.
 */
function bubble_sort($arr) {
        $count = count($arr);
        if($count = 0 || is_array($arr)) {
                echo 'NOT NULL ARRAY';
                return false;
        }
        for($i = 0; $i                 $flag = 1;
                for($j = $count - 1; $j > $i; $j--) {
                        if($arr[$j]                                 $tmp = $arr[$j]; //将数组的元素调换
                                $arr[$j] = $array[$j - 1];
                                $arr[$j - 1] = $tmp;
                                $flag = 0;
                        }
                if (1 == $flag)
                {
                     echo $i,'完成排序';
                     break;
                }
                }
        }
        return $arr;
}

例2

 代码如下 复制代码

//效率排序   
//冒泡排    $arr = array(-1,10,99,89,77,101,3,4,5,22,11,56,32);   
  //冒泡排序法   
$flag = false;   
function bubbleSort($myarr)   
{   
    $_temp = 0;   
    for ($i=0;$i     {   
        for ($j=0;$j         {   
            //如果前面的数比后面的数大,则两个数交换   
            if ($myarr[$j] > $myarr[$j+1])   
            {   
                $_temp = $myarr[$j];   
                $myarr[$j] = $myarr[$j+1];   
                $myarr[$j+1] = $_temp;   
                $flag = true;   
            }   
        }   
        //flage标志位,提升效率用   
        if (!$flag)   
        {   
            echo "已经是有序数组";   
            break;//已经是有序数组,直接退出   
        }   
        $flag = false;   
    }   
    return $myarr;   
}   
//原样输出   
function dump($string)   
{   
    echo "

";    <br>
    print_r($string);    <br>
    echo "
Copy after login
";   
}   
  dump(bubbleSort($arr));   
?>  
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!