Search code examples
phpalgorithmsortinginsertion-sort

Difference between these two implementations of Insertion Sort


I feel these two implementations are doing the same thing, but would be great if you can also let me know if they are (performance wise) doing the same thing (e.g. in terms of number of instructions executed). Thanks.

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

Solution

  • No they are not the same. The function sortOne is wrong implementation of insertion sort.

    The correct implementation of function sortOne is:

    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;
    }
    

    Considering the performance now, they basically have equal performance. Just by changing for loop to while loop, you wont be getting any performance change.