Last active
May 29, 2020 13:11
-
-
Save ichtrojan/e5a6de8b3211403184e32b9e1b029a1a to your computer and use it in GitHub Desktop.
Quicksort
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 generateArray() | |
{ | |
$array = []; | |
for ($i = 0; $i < 11; $i++) { | |
$array[$i] = mt_rand(-100, 100); | |
} | |
return $array; | |
} | |
function quicksort($array) { | |
if (count($array) == 0) return []; | |
$pivot_element = $array[0]; | |
$left_element = $right_element = array(); | |
for ($i = 1; $i < count($array); $i++) { | |
if ($array[$i] <$pivot_element) | |
$left_element[] = $array[$i]; | |
else | |
$right_element[] = $array[$i]; | |
} | |
return array_merge(quicksort($left_element), array($pivot_element), quicksort($right_element)); | |
} | |
$array = generateArray(); | |
print_r($array); | |
$start = microtime(true); | |
$array = quicksort($array); | |
$time = (microtime(true) - $start) * 1000; | |
echo "\n\nExecuted in {$time} seconds\n\n"; | |
echo "A billion times: ". (($time * 1000000000)/60/60)/24 ." days"; | |
print_r($array); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment