TheAlgorithms-PHP/Sorting/MergeSort.php

55 lines
1003 B
PHP
Raw Normal View History

<?php
/**
* Merge Sort
*
* @param array $arr
* @return array
*/
function mergeSort(array $arr)
{
2022-12-17 21:16:17 +02:00
if (count($arr) <= 1) {
return $arr;
}
$mid = floor(count($arr) / 2);
$leftArray = mergeSort(array_slice($arr, 0, $mid));
$rightArray = mergeSort(array_slice($arr, $mid));
2022-12-17 21:16:17 +02:00
return merge($leftArray, $rightArray);
}
/**
2022-12-17 21:16:17 +02:00
* @param array $leftArray
* @param array $rightArray
* @return array
*/
2022-12-17 21:16:17 +02:00
function merge(array $leftArray, array $rightArray)
{
2022-12-17 21:16:17 +02:00
$result = [];
$i = 0;
$j = 0;
while ($i < count($leftArray) && $j < count($rightArray)) {
if ($rightArray[$j] > $leftArray[$i]) {
$result[] = $leftArray[$i];
$i++;
} else {
2022-12-17 21:16:17 +02:00
$result[] = $rightArray[$j];
$j++;
}
}
2022-12-17 21:16:17 +02:00
while ($i < count($leftArray)) {
$result[] = $leftArray[$i];
$i++;
}
2022-12-17 21:16:17 +02:00
while ($j < count($rightArray)) {
$result[] = $rightArray[$j];
$j++;
}
return $result;
}