Created
January 18, 2023 02:41
-
-
Save flaviosilveira/e6f9f27193c936d4c6ba5775d32b5546 to your computer and use it in GitHub Desktop.
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 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