Skip to content

Instantly share code, notes, and snippets.

@trafficinc
Created December 30, 2017 15:10
Show Gist options
  • Save trafficinc/42100d87874403d8119b64a19e87d0c5 to your computer and use it in GitHub Desktop.
Save trafficinc/42100d87874403d8119b64a19e87d0c5 to your computer and use it in GitHub Desktop.
<?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