Created
March 24, 2012 21:38
-
-
Save cballou/2188280 to your computer and use it in GitHub Desktop.
A QUICK IMPLEMENTATION OF STRING SORT 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 | |
function sortString(&$s) { | |
$s = str_split($s); | |
sort($s); | |
$s = implode($s); | |
} | |
// example usage prints: | |
// 1223344789aaaaadddefffffhhhiillllnnoorrsssuuuuwyy | |
$string = 'ouhlasfuywernhlasdfoulnarfiuyadf1234987234sdfailh'; | |
sortString($string, strlen($string)); | |
echo $string . PHP_EOL; |
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 | |
function sortString($s) { | |
$left = $right = ''; | |
$l = strlen($s) - 1; | |
if ($l <= 0) return $s; | |
$pivot = floor($l/2); | |
do { | |
if ($l == $pivot) continue; | |
if ($s[$l] <= $s[$pivot]) $left .= $s[$l]; | |
else $right .= $s[$l]; | |
} while (--$l); | |
return sortString($left) . $s[$pivot] . sortString($right); | |
} | |
// example usage prints: | |
// 1223344789aaaaadddefffffhhhiillllnnoorrsssuuuuwyy | |
$string = 'ouhlasfuywernhlasdfoulnarfiuyadf1234987234sdfailh'; | |
$string = sortString($string); | |
echo $string . PHP_EOL; |
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 | |
/** | |
* A (slow) non-array based solution for sorting strings in PHP. | |
* | |
* @param &$s The string to be sorted | |
* @param $len The length of the string | |
* @param $curPos The current position being sorted (default = 0) | |
*/ | |
function sortString(&$s, $len = 0, $curPos = 0) { | |
if ($curPos === $len) return; | |
$nextPos = $curPos + 1; | |
while ($nextPos < $len) { | |
if ($s{$nextPos} < $s{$curPos}) { | |
$tmp = $s{$curPos}; | |
$s{$curPos} = $s{$nextPos}; | |
$s{$nextPos} = $tmp; | |
} | |
++$nextPos; | |
} | |
sortString($s, $len, $curPos + 1); | |
} | |
// example usage prints: | |
// 1223344789aaaaadddefffffhhhiillllnnoorrsssuuuuwyy | |
$string = 'ouhlasfuywernhlasdfoulnarfiuyadf1234987234sdfailh'; | |
sortString($string, strlen($string)); | |
echo $string . PHP_EOL; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment