插入排序的这两个实现之间的差异

时间:2017-04-16 11:18:23

标签: php algorithm sorting insertion-sort

我觉得这两个实现正在做同样的事情,但如果你能告诉我他们(表现明智)做同样的事情(例如在执行的指令数量方面)会很好。感谢。

<?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));

1 个答案:

答案 0 :(得分:0)

不,他们不一样。函数sortOne insertion sort的错误实现

函数sortOne的正确实现是:

for ($i = 1; $i < count($arr); $i++) {
    $instructionCount++;
    $temp = $arr[$i];
    for ($j = $i - 1; $j >= 0 && ($arr[$j] > $temp); $j--) {
        $instructionCount++;
        $arr[$j + 1] = $arr[$j];                
    }
    $arr[$j + 1] = temp;
}

考虑到现在的表现,它们基本上具有相同的性能。只需将for循环更改为while循环,就不会有任何性能变化。

相关问题