从来没有经历过面试。准备去大城市看看。从网上找点面试题看看。
八大排序算法
冒泡
// 冒泡排序
function bubble($arr)
{
$minIndex = 0;
$maxIndex = count($arr) - 1;
for ($i = $minIndex; $i <= $maxIndex; $i++) {
for ($j = 0; $j < $maxIndex - $i; $j++) {
if ($arr[$j] > $arr[$j + 1]) {
$tmp = $arr[$j + 1];
$arr[$j + 1] = $arr[$j];
$arr[$j] = $tmp;
}
}
}
return $arr;
}
// 排序算法优化:跑完一趟就判断一次原数组现在是否有序,如果有序;直接 return
function bubble(&$arr)
{
$minIndex = 0;
$maxIndex = count($arr) - 1;
for ($i = $minIndex; $i <= $maxIndex; $i++) {
$isOrdered = 0;
for ($j = 0; $j < $maxIndex - $i; $j++) {
if ($arr[$j] > $arr[$j + 1]) {
$tmp = $arr[$j + 1];
$arr[$j + 1] = $arr[$j];
$arr[$j] = $tmp;
$isOrdered = 1;
}
}
if (!$isOrdered) {
return $arr;
}
}
return $arr;
}
// 优化 2
function bubble(&$arr)
{
$minIndex = 0;
$maxIndex = count($arr) - 1;
$currentSwapIndex = 0;
$maxSwapIndex = $maxIndex;
for ($i = $minIndex; $i <= $maxIndex; $i++) {
$isOrdered = 0;
for ($j = 0; $j < $maxSwapIndex; $j++) {
if ($arr[$j] > $arr[$j + 1]) {
swap($arr[$j], $arr[$j + 1]);
$isOrdered = 1;
$currentSwapIndex = $j;
}
}
if (!$isOrdered) {
return $arr;
}
$maxSwapIndex = $currentSwapIndex;
}
return $arr;
}
时间复杂度:
(n-1) + (n-2) + ... + 1 = n * (n - 1) / 2
=>
n(n-1)/2 = (n^2 - n) / 2
=>O(N^2)
优化后的冒泡排序时间复杂度最优情况是
O(n)
选择
function pick($arr)
{
$minIndex = 0;
$maxIndex = count($arr) - 1;
for ($i = $minIndex; $i <= $maxIndex; $i++) {
$currentMinIndex = $i;
for ($j = $i; $j < $maxIndex; $j++) {
if ($arr[$currentMinIndex] > $arr[$j + 1]) {
$currentMinIndex = $j+1;
}
}
if ($i !== $currentMinIndex) {
swap($arr[$i], $arr[$currentMinIndex]);
}
}
return $arr;
}
function swap(&$a, &$b)
{
$tmp = $a;
$a = $b;
$b = $tmp;
return true;
}
之所以叫选择排序。是因为,它每次都会选择未排序中的最小的,和刚刚排完序的元素进行比较。