這兩個實現之間的區別我覺得這兩個實現都在做同樣的事情,但如果你可以讓我知道它們是否(性能明智)做同樣的事情(例如在數字方面的指令執行)。謝謝。插入排序
<?php
$arr = array(10, 2, 3, 14, 16);
function sortOne($arr) {
$instructionCount = 0;
for ($i = 1; $i < count($arr); $i++) {
$instructionCount++;
for ($j = $i - 1; $j >= 0 && ($arr[$j] > $arr[$i]); $j--) {
$instructionCount++;
$tmp = $arr[$i];
$arr[$i] = $arr[$j];
$arr[$j] = $tmp;
}
}
echo "\nTotal Instructions for Sort One: $instructionCount\n";
return $arr;
}
function sortTwo($array) {
$instructionCount = 0;
for($j=1; $j < count($array); $j++){
$instructionCount++;
$temp = $array[$j];
$i = $j;
while(($i >= 1) && ($array[$i-1] > $temp)){
$instructionCount++;
$array[$i] = $array[$i-1];
$i--;
}
$array[$i] = $temp;
}
echo "\nTotal Instructions for Sort Two: $instructionCount\n";
return $array;
}
var_dump(sortOne($arr));
我只想指出,你可以使用[sort](http://php.net/manual/en/function.sort.php)函數來排序你的數組 –
謝謝@AmrAly我知道,但我是對算法分析感興趣否則肯定會使用庫函數 –
@SoftwareGuy你的第一個函數不能正確地對數組進行排序。 –