Created
August 23, 2016 15:54
-
-
Save antoniopicone/057c5646a4800fe95c8cd3a9eba56163 to your computer and use it in GitHub Desktop.
A simple implementation of Merge Sort in PHP
This file contains 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) { | |
if( sizeof($array) == 1 ) return $array; | |
$middle = floor(sizeof($array) / 2); | |
$l_arr = mergeSort( array_slice( $array, 0, $middle)); | |
$r_arr = mergeSort( array_slice( $array, $middle)); | |
$l_ptr = $r_ptr = $d_ptr = 0; | |
$result = array(); | |
while($d_ptr < sizeof($array)) { | |
if( $l_ptr == sizeof($l_arr) ) { | |
$result[$d_ptr] = $r_arr[$r_ptr]; | |
$r_ptr++; | |
} | |
else if( $r_ptr == sizeof($r_arr)) { | |
$result[$d_ptr] = $l_arr[$l_ptr]; | |
$l_ptr++; | |
} | |
else if( $l_arr[$l_ptr] < $r_arr[$r_ptr] ) { | |
$result[$d_ptr] = $l_arr[$l_ptr]; | |
$l_ptr++; | |
} | |
else { | |
$result[$d_ptr] = $r_arr[$r_ptr]; | |
$r_ptr++; | |
} | |
$d_ptr++; | |
} | |
return $result; | |
} | |
$arr = array(3,5,1,2,8,7,6,9,4); | |
echo implode(',', mergeSort($arr)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment