Created
March 17, 2013 08:39
-
-
Save ackintosh/5180695 to your computer and use it in GitHub Desktop.
Quick sort in PHP
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 partition(Array &$array, $left, $right, $pivot) | |
{ | |
$il = $left; | |
$ir = $right - 1; | |
while ($il < $ir) { | |
while ($il < $right && $array[$il] <= $pivot) $il++; | |
while ($ir >= $left && $array[$ir] > $pivot) $ir--; | |
if ($il >= $ir) break; | |
list($array[$il], $array[$ir]) = array($array[$ir], $array[$il]); | |
} | |
return $ir + 1; | |
} | |
function quicksort(Array &$array) | |
{ | |
_quicksort($array, 0, count($array)); | |
} | |
function _quicksort(&$array, $left, $right) | |
{ | |
if ($right - $left <= 1) return; | |
$pivotIdx = findPivotIdx($array, $left, $right); | |
if ($pivotIdx < 0) return; | |
$mid = partition($array, $left, $right, $array[$pivotIdx]); | |
_quicksort($array, $left, $mid); | |
_quicksort($array, $mid, $right); | |
} | |
function findPivotIdx($array, $left, $right) | |
{ | |
if ($right - $left <= 1) return -1; | |
$t = $array[$left]; | |
for ($i = $left + 1; $i < $right; $i++) { | |
if ($array[$i] === $t) continue; | |
if ($array[$i] < $t) return $i; | |
return $left; | |
} | |
return -1; | |
} | |
$ar = array(7,2,1,6,8,4); | |
quicksort($ar); | |
var_dump($ar); | |
/* | |
array(6) { | |
[0]=> | |
int(1) | |
[1]=> | |
int(2) | |
[2]=> | |
int(4) | |
[3]=> | |
int(6) | |
[4]=> | |
int(7) | |
[5]=> | |
int(8) | |
} | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment