【问题标题】:PHP array sort using Bubble approach [duplicate]使用冒泡方法的PHP数组排序[重复]
【发布时间】:2016-11-29 08:06:37
【问题描述】:

我有一个数组比如 $arr = array(1,3,2,8,5,7,4,6​​,0);

如何使用冒泡排序方法进行自定义排序?

谢谢

【问题讨论】:

标签: php arrays


【解决方案1】:
$arr = array(7, 3, 9, 6, 5, 1, 2, 0, 8, 4);
$sortedArr = bubbleSort($arr);
var_dump($sortedArr);

function bubbleSort(array $arr) {
    $sorted = false;
    while (false === $sorted) {
        $sorted = true;
        for ($i = 0; $i < count($arr)-1; ++$i) {
            $current = $arr[$i];
            $next = $arr[$i+1];
            if ($next < $current) {
                $arr[$i] = $next;
                $arr[$i+1] = $current;
                $sorted = false;
            }
        }
    }
    return $arr;
}

echo "<pre>";
print_r(bubbleSort($arr)); 

http://blog.richardknop.com/2012/06/bubble-sort-algorithm-php-implementation/

【讨论】:

    【解决方案2】:

    给你:

    $a=array(5,4,3,1,2);
    for($j=0; $j < count($a)-1; $j++) {
        $swapped=false;
        $i=0;
        while ($i < count($a)-1)  {
            if( $a[$i] > $a[$i+1]) {
                $c=$a[$i];
                $a[$i]=$a[$i+1];
                $a[$i+1]=$c;
                $swapped=true;
           }
           ++$i;
        } 
    
        if( !$swapped )
            break;
    }
    print_r($a);
    

    输出:

    Array
    (
        [0] => 1
        [1] => 2
        [2] => 3
        [3] => 4
        [4] => 5
    )
    

    【讨论】:

      猜你喜欢
      • 2021-06-14
      • 2021-03-24
      • 1970-01-01
      • 2020-05-17
      • 2013-09-09
      • 2016-03-03
      • 2016-02-10
      • 1970-01-01
      • 2013-09-28
      相关资源
      最近更新 更多