Implementing insertion sort

We will implement the insertion sort in a similar way to the other two sorts but with a subtle difference. This time, we will pass the array as a reference. By doing so, we will not require any return value from the function. We can also pass the argument by value and return the array at the end of the function if we want. Here is the code for this:

function insertionSort(array &$arr) { 
$len = count($arr);
for ($i = 1; $i < $len; $i++) {
$key = $arr[$i];
$j = $i - 1;

while($j >= 0 && $arr[$j] > $key) {
$arr[$j+1] = $arr[$j];
$j--;
}
$arr[$j+1] = $key;
}
}

The parameter array is passed to the function by reference (&$arr). Thus, the original array, not a copy of it, will be modified directly. Now, we want to run the code and check the output. For this, we have to run the following code:

$arr = [20, 45, 93, 67, 10, 97, 52, 88, 33, 92];

insertionSort($arr);
echo implode(",", $arr);

This will produce the same output we had in the previous two cases. The only difference is that we are not expecting any return array from the function and not storing it into any new variable.

If we pass the array by reference, then we do not have to return the array. The passed array will be modified inside the function. It is down to choice how we want to achieve the sorting.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset