Created
August 31, 2012 13:49
-
-
Save wangshijun/3552889 to your computer and use it in GitHub Desktop.
php: quick sort algorithm implemented in php
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 | |
$data = array(55,41,59,26,53,58,97,93); | |
quicksort(0, sizeof($data)-1); | |
function quicksort($lower, $upper) { | |
global $data; | |
if ($lower >= $upper) { | |
return; | |
} | |
$m = $lower; | |
echo str_repeat("=", 80), PHP_EOL; | |
// partition the array on $data[$lower] | |
for ($i=$lower+1; $i<=$upper; $i++) { | |
if ($data[$i] < $data[$lower]) { | |
$tmp = $data[++$m]; | |
$data[$m] = $data[$i]; | |
$data[$i] = $tmp; | |
print_array($data); | |
} | |
} | |
// swap the sential node with $data[$m] | |
$tmp = $data[$m]; | |
$data[$m] = $data[$lower]; | |
$data[$lower] = $tmp; | |
print_array($data); | |
// quick sort the tow parts recursively | |
quicksort($lower, $m-1); | |
quicksort($m+1, $upper); | |
} | |
function print_array($data, $newlineCount = 1) { | |
echo implode("->", $data), str_repeat(PHP_EOL, $newlineCount); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment