Merge Sort

Sort an array using the merge sort algorithm with O(n log n) time complexity.

Code

Algorithms
function mergeSort($a) {
    if (count($a) <= 1) return $a;
    $mid = (int)(count($a) / 2);
    $left = mergeSort(array_slice($a, 0, $mid));
    $right = mergeSort(array_slice($a, $mid));
    $result = [];
    while (count($left) && count($right)) {
        $result[] = $left[0] <= $right[0] ? array_shift($left) : array_shift($right);
    }
    return array_merge($result, $left, $right);
}
mergeSort($arr);

Parameters

Array to sort

Server

More PHP Snippets