冒泡排序

<?php
/**
 * Created by PhpStorm.
 * User: huangye
 * Date: 2015/8/26
 * Time: 18:57
 */

//从小到大排序
function bubble_sort_1($a_data)
{
    $len = count($a_data);
    for ($i = 0; $i < $len; $i++) {
        for ($j = 0; $j < $len - $i - 1; $j++) {
            if ($a_data[$j] > $a_data[$j + 1]) {
                $temp           = $a_data[$j];
                $a_data[$j]     = $a_data[$j + 1];
                $a_data[$j + 1] = $temp;
            }
        }
    }

    return $a_data;
}

$a_data = array(20, 40, 60, 80, 30, 70, 90, 10, 50, 0);
var_dump(bubble_sort_1($a_data));

/**
 * 冒泡排序改进版
 * 从小到大排序
 * @param $a_data
 * @return mixed
 */
function bubble_sort_2($a_data)
{
    $len  = count($a_data);
    $flag = 1; //如果在内循环内没有发生交换,则$flag为0,此时可知数组中的数字已经有序了,不用在继续比较
    for ($i=0; $i<$len && $flag==1; $i++) {
        $flag = 0;
        for ($j=0; $j<$len-$i-1; $j++) {
            if ($a_data[$j+1] < $a_data[$j]) {
                $tmp          = $a_data[$j];
                $a_data[$j]   = $a_data[$j+1];
                $a_data[$j+1] = $tmp;
                $flag = 1;
            }
        }
    }

    return $a_data;
}

$a_data = array(20, 40, 60, 80, 30, 70, 90, 10, 50, 0);
var_dump(bubble_sort_2($a_data));

 

你可能感兴趣的:(冒泡排序)