Created
September 17, 2019 04:16
-
-
Save Jason-cqtan/8efa7fe6213ecc9c5f0c301441ee9185 to your computer and use it in GitHub Desktop.
php冒泡排序算法
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 冒泡排序算法 | |
* @param array $arr | |
* @return array | |
*/ | |
function bubble_sort($arr) { | |
// 判断参数是否为数组,且不为空 | |
if (!is_array($arr) || empty($arr)) { | |
return $arr; | |
} | |
$len = count($arr); | |
// 循环需要冒泡的轮数 | |
for ($i = 1; $i < $len; $i++) { | |
// 循环每轮需要比较的次数 | |
for ($j = 0; $j < $len - $i; $j++) { | |
// 大的数,交换位置,往后挪 | |
if ($arr[$j] > $arr[$j + 1]) { | |
list($arr[$j],$arr[$j + 1]) = [$arr[$j + 1],$arr[$j]]; | |
// $temp = $arr[$j + 1]; | |
// $arr[$j + 1] = $arr[$j]; | |
// $arr[$j] = $temp; | |
} | |
} | |
} | |
return $arr; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment