May 2017
Intermediate to advanced
340 pages
8h 16m
English
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 ...
Read now
Unlock full access