Created
March 17, 2013 07:59
-
-
Save ackintosh/5180548 to your computer and use it in GitHub Desktop.
Merge sort in 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 | |
function mergesort(&$array) | |
{ | |
_mergesort($array, 0, count($array)); | |
} | |
function _mergesort(&$array, $left, $right) | |
{ | |
if ($right - $left <= 1) return; | |
$mid = intval($left + ($right - $left) / 2); | |
_mergesort($array, $left, $mid); | |
_mergesort($array, $mid, $right); | |
merge($array, $left, $mid, $right); | |
} | |
function merge(&$array, $left, $mid, $right) | |
{ | |
$l_index = $left; | |
$r_index = $mid; | |
$result = array(); | |
while ($l_index < $mid && $r_index < $right) { | |
if ($array[$l_index] <= $array[$r_index]) { | |
$result[] = $array[$l_index]; | |
$l_index++; | |
} else { | |
$result[] = $array[$r_index]; | |
$r_index++; | |
} | |
} | |
while ($l_index < $mid) { | |
$result[] = $array[$l_index]; | |
$l_index++; | |
} | |
while ($r_index < $right) { | |
$result[] = $array[$r_index]; | |
$r_index++; | |
} | |
arrayCopy($result, $array, $left, $right); | |
} | |
function arrayCopy($resource, &$array, $start, $end) | |
{ | |
$res_index = 0; | |
for ($i = $start; $i < $end; $i++) { | |
$array[$i] = $resource[$res_index]; | |
$res_index++; | |
} | |
} | |
$ar = array(3,1,5,11,12,3,9); | |
mergesort($ar); | |
var_dump($ar); | |
/* | |
array(7) { | |
[0]=> | |
int(1) | |
[1]=> | |
int(3) | |
[2]=> | |
int(3) | |
[3]=> | |
int(5) | |
[4]=> | |
int(9) | |
[5]=> | |
int(11) | |
[6]=> | |
int(12) | |
} | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment