Skip to content

Instantly share code, notes, and snippets.

@flaviosilveira
Created January 18, 2023 02:41
Show Gist options
  • Save flaviosilveira/e6f9f27193c936d4c6ba5775d32b5546 to your computer and use it in GitHub Desktop.
Save flaviosilveira/e6f9f27193c936d4c6ba5775d32b5546 to your computer and use it in GitHub Desktop.
<?php
function merge_sort($my_array){
echo "chamou merge_sort\n";
if(count($my_array) == 1 ) {
return $my_array;
}
$mid = count($my_array) / 2;
$left = array_slice($my_array, 0, (int)$mid);
$right = array_slice($my_array, (int)$mid);
$left = merge_sort($left);
$right = merge_sort($right);
return merge($left, $right);
}
function merge($left, $right){
echo "chamou merge\n";
var_dump($left, $right);
$res = array();
$i = $j = 0;
while ($i < count($left) && $j < count($right)){
if($left[$i] < $right[$j]){
$res[] = $left[$i];
$i++;
}else{
$res[] = $right[$j];
$j++;
}
}
while ($i < count($left)){
$res[] = $left[$i];
$i++;
}
while ($j < count($right)){
$res[] = $right[$j];
$j++;
}
return $res;
}
$test_array = array(6, 5, 4, 3, 2, 1);
echo "Original Array : ";
echo implode(', ',$test_array );
echo "\nSorted Array :";
echo implode(', ',merge_sort($test_array))."\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment