Created
December 11, 2021 16:00
-
-
Save showsky/8e40d26501a34b05bddd4e9693003d89 to your computer and use it in GitHub Desktop.
(PHP) Merge Sort
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function mergeSort(array &$array, int $front, int $end) { | |
if ($front < $end) { | |
$mid = (int) (($front + $end) / 2); | |
mergeSort($array, $front, $mid); | |
mergeSort($array, $mid + 1, $end); | |
merge($array, $front, $mid, $end); | |
} | |
} | |
function merge(array &$array, int $front, int $mid, int $end) { | |
$array1 = array_slice($array, $front, $mid + 1); | |
$array2 = array_slice($array, $mid + 1); | |
$array1[] = PHP_INT_MAX; | |
$array2[] = PHP_INT_MAX; | |
$indexLeft = 0; | |
$indexRight = 0; | |
for ($i = $front; $i <= $end; $i++) { | |
if ($array1[$indexLeft] < $array2[$indexRight]) { | |
$array[$i] = $array1[$indexLeft]; | |
$indexLeft++; | |
} else { | |
$array[$i] = $array2[$indexRight]; | |
$indexRight++; | |
} | |
} | |
} | |
/** Main **/ | |
$array = [10, 4, 11, 2, 1]; | |
$front = 0; | |
$end = count($array) - 1; | |
mergeSort($array, $front, $end); | |
var_dump($array); | |
/* | |
array(5) { | |
[0]=> | |
int(1) | |
[1]=> | |
int(2) | |
[2]=> | |
int(4) | |
[3]=> | |
int(10) | |
[4]=> | |
int(11) | |
} | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
refer to https://alrightchiu.github.io/SecondRound/comparison-sort-merge-sorthe-bing-pai-xu-fa.html