Merge pull request #295 from git-zjx/patch-5

增加冒泡排序和选择排序
This commit is contained in:
wangzheng0822 2019-04-17 10:58:23 +08:00 committed by GitHub
commit 9de7431fcd
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -1,5 +1,27 @@
<?php
// 冒泡排序
function bubbleSort(&$arr)
{
$length = count($arr);
if ($length <= 1) return;
for ($i = 0; $i < $length; $i++) {
$flag = false;
for ($j = 0; $j < $length - $i - 1; $j++) {
if ($arr[$i] > $arr[$j + 1]) {
$tmp = $arr[$j];
$arr[$j] = $arr[$j + 1];
$arr[$j + 1] = $tmp;
$flag = true;
}
}
if (!$flag) {
break;
}
}
}
// 插入排序
function insertionSort(&$arr)
{
$n = count($arr);
@ -20,6 +42,26 @@ function insertionSort(&$arr)
}
}
// 选择排序
function selectionSort(&$arr)
{
$length = count($arr);
if ($length <= 1) return;
for ($i = 0; $i < $length - 1; $i++) {
//先假设最小的值的位置
$p = $i;
for ($j = $i + 1; $j < $length; $j++) {
if ($arr[$p] > $arr[$j]) {
$p = $j;
}
}
$tmp = $arr[$p];
$arr[$p] = $arr[$i];
$arr[$i] = $tmp;
}
}
$arr = [1,4,6,2,3,5,4];
insertionSort($arr);
var_dump($arr);