Home  >  Article  >  Backend Development  >  浅谈php冒泡排序_php实例

浅谈php冒泡排序_php实例

WBOY
WBOYOriginal
2016-05-16 20:26:561031browse

PHP实现的代码先奉上:

复制代码 代码如下:

function bubble_sort($array) {
    for ($i = 0; $i         for ($j = 0; $j             if ($array[$j] > $array[$j + 1]) {    //按升序排序
                $temp = $array[$j];
                $array[$j] = $array[$j + 1];
                $array[$j + 1] = $temp;
            }
        }
    }
    return $array;
}

$a = array(5, 1, 4, 7);

代码执行过程:

复制代码 代码如下:

i = 0;
  j = 0;
  if($arr[0] > $arr[1]) => 5 > 1 条件成立,交换位置,形成新的数组 =>  1 5 4 7  j++
  if($arr[1] > $arr[2]) => 5 > 4 条件成立,交换位置, 形成新的数组 =>  1 4 5 7  j++
  if($arr[2] > $arr[3]) => 5 > 7 条件不成立 ,数组保持不变 , 1 4 5 7 j++ j=3 退出内层循环, i++

依次类推吧。

Statement:
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