Skip to content

Instantly share code, notes, and snippets.

@wuhei
Created May 5, 2023 12:58
Show Gist options
  • Save wuhei/5ea915478c22ab92cc00f0194871b81f to your computer and use it in GitHub Desktop.
Save wuhei/5ea915478c22ab92cc00f0194871b81f to your computer and use it in GitHub Desktop.
Quicksort PHP SplFixedArray in PHP5.6, based on a key
/**
* Quicksorting (with partition) implementation to sort SplFixedArray on a specific key,
* I could not find this and I needed this because I'm stuck on PHP5.6 at work -- 2023-05-04 wuhei
*
* @param $arr SplFixedArray, array to sort
* @param $key mixed, array key to sort on
* @param $desc bool if true, sort descending
* @param $leftIndex int, left index of the array to sort, defaults to 0
* @param $rightIndex int, right index of the array to sort, defaults to count($arr) - 1
* @return mixed
* @throws Exception, if you forgot something useful
* @author 2023-05-04 wuhei
*/
public function quickSort(&$arr = NULL, $key = NULL, $desc = NULL, $leftIndex, $rightIndex) {
if(NULL === $arr) {
throw new Exception("No SplFixedArray provided");
}
if(NULL === $key) {
throw new Exception("Nessun key to order on provided");
}
if($desc !== true) {
$desc = false;
}
// single element array, return and done
if(count($arr) <= 1) {
return $arr;
}
if(NULL === $leftIndex) {
$leftIndex = 0;
}
if(NULL === $rightIndex) {
$rightIndex = count($arr) - 1;
}
if($leftIndex < $rightIndex) {
$pivot = $this->partition($arr, $key, $leftIndex, $rightIndex);
quickSort($arr, $key, NULL, $leftIndex, $pivot - 1);
quickSort($arr, $key, NULL, $pivot + 1, $rightIndex);
}
if($desc) {
// reverse the array
$l = $arr->count();
$reverseArr = new SplFixedArray($l);
$z = 0;
for($i=$l-1;$i>=0;$i--) {
$reverseArr[$z] = $arr[$i];
$z++;
}
$arr = $reverseArr;
}
return $arr;
}
public function partition(&$arr = NULL,$key = NULL, $leftIndex = NULL ,$rightIndex = NULL) {
if(NULL === $arr) {
throw new Exception("no SplFixedArray given");
}
if(NULL === $key) {
throw new Exception("no key to order on provided");
}
$pivot = &$arr[$rightIndex];
$i = $leftIndex;
for($j=$leftIndex;$j<$rightIndex;$j++) {
if($arr[$j][$key] <= $pivot[$key]){
$tmp = $arr[$i];
$arr[$i] = $arr[$j];
$arr[$j] = $tmp;
$i++;
}
}
$tmp = $arr[$i];
$arr[$i] = $arr[$rightIndex];
$arr[$rightIndex] = $tmp;
return $i;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment