Last active
March 4, 2021 21:12
-
-
Save HallexCosta/e253b2ecb755cc115d4336bce2ca5ddb to your computer and use it in GitHub Desktop.
MergeSort Algorithm with PHP
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 | |
require_once './Merge.php'; | |
$a = [15, 5, 24, 8, 1, 3, 16, 10, 20]; | |
Merge::display($a); // output: [15, 5, 24, 8, 1, 3, 16, 10, 20] | |
Merge::sort($a, 0, count($a) - 1); | |
Merge::display($a); // output: [1, 3, 5, 8, 10, 15, 16, 20, 24] |
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 | |
/** | |
* class Merge | |
*/ | |
class Merge { | |
/** | |
* sort | |
* @param array &$a (Pointer) | |
* @param int $lb | |
* @param int $ub | |
* @return void | |
*/ | |
public static function sort(array &$a, int $lb, int $ub): void { | |
if ($lb < $ub) { | |
$mid = intval(($lb + $ub) / 2); | |
Merge::sort($a, $lb, $mid); | |
Merge::sort($a, $mid + 1, $ub); | |
Merge::concat($a, $lb, $mid, $ub); | |
} | |
} | |
/** | |
* concat | |
* @param array &$a (Pointer) | |
* @param int $lb | |
* @param int $mid | |
* @param int $ub | |
* @return void | |
*/ | |
public static function concat(array &$a, int $lb, int $mid, int $ub): void { | |
$i = $lb; | |
$j = $mid + 1; | |
$k = $lb; | |
$b = []; | |
while ($i <= $mid && $j <= $ub) { | |
if ($a[$i] <= $a[$j]) { | |
$b[$k] = $a[$i++]; | |
} else { | |
$b[$k] = $a[$j++]; | |
} | |
$k++; | |
} | |
if ($i > $mid) { | |
while ($j <= $ub) { | |
$b[$k++] = $a[$j++]; | |
} | |
} else { | |
while ($i <= $mid) { | |
$b[$k++] = $a[$i++]; | |
} | |
} | |
for ($k = $lb; $k <= $ub; $k++) { | |
$a[$k] = $b[$k]; | |
} | |
} | |
/** | |
* concat | |
* @param array &$a (Pointer) | |
* @return void | |
*/ | |
public static function display(array &$a): void { | |
$data = join(', ', $a); | |
echo '['. $data .']'; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment