Skip to content

Instantly share code, notes, and snippets.

@cballou
Created March 24, 2012 21:38
Show Gist options
  • Save cballou/2188280 to your computer and use it in GitHub Desktop.
Save cballou/2188280 to your computer and use it in GitHub Desktop.
A QUICK IMPLEMENTATION OF STRING SORT IN PHP
<?php
function sortString(&amp;$s) {
$s = str_split($s);
sort($s);
$s = implode($s);
}
// example usage prints:
// 1223344789aaaaadddefffffhhhiillllnnoorrsssuuuuwyy
$string = 'ouhlasfuywernhlasdfoulnarfiuyadf1234987234sdfailh';
sortString($string, strlen($string));
echo $string . PHP_EOL;
<?php
function sortString($s) {
$left = $right = '';
$l = strlen($s) - 1;
if ($l &lt;= 0) return $s;
$pivot = floor($l/2);
do {
if ($l == $pivot) continue;
if ($s[$l] &lt;= $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;
<?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 &lt; $len) {
if ($s{$nextPos} &lt; $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