Implementing merge sort

We will first write the divide part followed by the merge or conquer part. PHP has some built-in functions to split an array. We will use the array_slice function to do the splitting. Here is the code to do this:

function mergeSort(array $arr): array { 
$len = count($arr);
$mid = (int) $len / 2;
if ($len == 1)
return $arr;

$left = mergeSort(array_slice($arr, 0, $mid));
$right = mergeSort(array_slice($arr, $mid));

return merge($left, $right);
}

As we can see from the code, we split the array in a recursive way until the array size becomes 1. When array size is 1, we start to merge backward, just like the last image. Here is the code for the merge function, which will take two arrays, and merge them into one as per our pseudocode:

function merge(array $left, array $right): array { 
$combined = [];
$countLeft = count($left);
$countRight = count($right);
$leftIndex = $rightIndex = 0;

while ($leftIndex < $countLeft && $rightIndex < $countRight) {
if ($left[$leftIndex] > $right[$rightIndex]) {
$combined[] = $right[$rightIndex];
$rightIndex++;
} else {
$combined[] = $left[$leftIndex];
$leftIndex++;
}
}
while ($leftIndex < $countLeft) {
$combined[] = $left[$leftIndex];
$leftIndex++;
}
while ($rightIndex < $countRight) {
$combined[] = $right[$rightIndex];
$rightIndex++;
}
return $combined;
}

The code is now complete as we have merged the two supplied arrays and returned the combined results to the mergeSort function. We have just solved the problem recursively. If you run the following code, you will have a list of items in ascending order:

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

$arr = mergeSort($arr);
echo implode(",", $arr);

Now, let's explore the complexity for merge sort.

..................Content has been hidden....................

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