Last active
June 12, 2017 14:59
-
-
Save wenpeng/9edd15004c78816f2d0e291f8e670c1a 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
<?php | |
$arr = [1, 3, 4, 6, 5, 7, 2, 8, 9]; | |
# 快速排序 | |
function quickSort($arr) { | |
$len = count($arr); | |
if ($len < 2) { | |
return $arr; | |
} | |
$left = $right = []; | |
$base = array_shift($arr); | |
foreach ($arr as $val) { | |
if ($val > $base) { | |
$left[] = $val; | |
} else { | |
$right[] = $val; | |
} | |
} | |
if ($left) { | |
$left = quickSort($left); | |
} | |
if ($right) { | |
$right = quickSort($right); | |
} | |
return array_merge($left, [$base], $right); | |
} | |
print_r(quickSort($arr)); | |
# 插入算法 | |
function insertSort($arr) | |
{ | |
$len = count($arr); | |
if ($len < 2) { | |
return $arr; | |
} | |
for ($i = 1; $i < $len; $i++) { | |
$val = $arr[$i]; | |
$pos = $i - 1; | |
while (($pos > -1) && ($val > $arr[$pos])) { | |
$arr[$pos + 1] = $arr[$pos]; | |
$pos--; | |
} | |
$pos++; | |
if ($pos !== $i) { | |
$arr[$pos] = $val; | |
} | |
} | |
return $arr; | |
} | |
print_r(insertSort($arr)); | |
# 冒泡算法 | |
function bubblSort($arr) | |
{ | |
$len = count($arr); | |
if ($len < 2) { | |
return $arr; | |
} | |
$max = $len - 1; | |
for ($i = 0; $i < $max; $i++) { | |
for ($j = 0; $j < $max - $i; $j++) { | |
if ($arr[$j] < $arr[$j + 1]) { | |
$tmp = $arr[$j]; | |
$arr[$j] = $arr[$j + 1]; | |
$arr[$j + 1] = $tmp; | |
} | |
} | |
} | |
return $arr; | |
} | |
print_r(bubblSort($arr)); | |
# 选择算法 | |
function selectSort($arr) | |
{ | |
$len = count($arr); | |
if ($len < 2) { | |
return $arr; | |
} | |
$max = $len - 1; | |
for ($i = 0; $i < $max; $i++) { | |
$index = $i; | |
for ($n = $i + 1; $n < $len; $n++) { | |
if ($arr[$n] > $arr[$index]) { | |
$index = $n; | |
} | |
} | |
if ($index !== $i) { | |
$tmp = $arr[$i]; | |
$arr[$i] = $arr[$index]; | |
$arr[$index] = $tmp; | |
} | |
} | |
return $arr; | |
} | |
print_r(selectSort($arr)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment