Created
December 30, 2017 15:10
-
-
Save trafficinc/42100d87874403d8119b64a19e87d0c5 to your computer and use it in GitHub Desktop.
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 | |
$unsorted = array(43,21,2,1,9,24,2,99,23,8,7,114,92,5); | |
function quick_sort($array) | |
{ | |
// find array size | |
$length = count($array); | |
// base case test, if array of length 0 then just return array to caller | |
if($length <= 1){ | |
return $array; | |
} | |
else{ | |
// select an item to act as our pivot point, since list is unsorted first position is easiest | |
$pivot = $array[0]; | |
// declare our two arrays to act as partitions | |
$left = $right = array(); | |
// loop and compare each item in the array to the pivot value, place item in appropriate partition | |
for($i = 1; $i < count($array); $i++) | |
{ | |
if($array[$i] < $pivot){ | |
$left[] = $array[$i]; | |
} | |
else{ | |
$right[] = $array[$i]; | |
} | |
} | |
// use recursion to now sort the left and right lists | |
return array_merge(quick_sort($left), array($pivot), quick_sort($right)); | |
} | |
} | |
$sorted = quick_sort($unsorted); | |
print_r($sorted); | |
/* | |
Array | |
( | |
[0] => 1 | |
[1] => 2 | |
[2] => 2 | |
[3] => 5 | |
[4] => 7 | |
[5] => 8 | |
[6] => 9 | |
[7] => 21 | |
[8] => 23 | |
[9] => 24 | |
[10] => 43 | |
[11] => 92 | |
[12] => 99 | |
[13] => 114 | |
) | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment