![Recursive bubble sort algorithm in PHP Recursive bubble sort algorithm in PHP](https://swww.com.pl/media/img/post/32_head.jpg)
Recursive bubble sort algorithm in PHP
Created:06 Apr 2017 17:48:19 , in Maths
A quick and recursive bubble sort script.
/* Class: RecursiveSort - recursive sort algorithms container
Author : Sylwester Wojnowski
WWW : wojnowski.net.pl
Methods:
public static bubble($list, $compare)
Description:
sort items in $list
Parameters:
$list array - items (integers, strings, arrays, objects)
$compare - anonymous function - function used for comparisons,
accepts two arguments, compares them and returns bool true or false.
*/
class RecursiveSort{
public static function bubble($list,$compare = false,$p = 0){
$n = count($list);
$tmp = null;
$i = 0;
if(!$compare){
$compare = function($a,$b){ return $a > $b; };
}
if( $n < 2 ) { return $list;}
$p = $p === 0 ? $n - 1 : $p - 1;
while( $i <= $p - 1 ){
if($compare($list[$i],$list[$i+1])){
$tmp = $list[$i];
$list[$i] = $list[$i+1];
$list[$i+1] = $tmp;
}
$i++;
}
if ( $p === 1 ){ return $list;}
return self::bubble( $list,$compare,$p );
}
}
Sorting items with RecursiveSort::bubble
RecursiveSort::bubble sorts numbers in ascending order by default. It uses built-in comparison function for this.
Sorting objects in ascending order:
RecursiveSort::bubble(array(9,-22,8,1,35,7,0))
Sorting objects in descending order:
RecursiveSort::bubble(array(9,-22,8,1,35,7,0),function($a,$b){return $a < $b;})
Sorting arrays in descending order:
RecursiveSort::bubble(
array(
array(4,2),
array(3,5),
array(5,2)
),
function($a,$b){
return array_sum($a) < array_sum($b);
}
);
Sorting object in descending order:
$products = array(
(object)array("price" => 200),
(object)array("price" => 700),
(object)array("price" => 100),
);
RecursiveSort::bubble(
$products,
function($a,$b){
return $a -> price < $b -> price;
}
);
This post was updated on 06 Oct 2021 21:31:44
Author, Copyright and citation
Author
![Sylwester Wojnowski](https://swww.com.pl/media/img/gravatar_110.png)
Author of the this article - Sylwester Wojnowski - is a sWWW web developer. He has been writing computer code for the websites and web applications since 1998.
Copyrights
©Copyright, 2024 Sylwester Wojnowski. This article may not be reproduced or published as a whole or in parts without permission from the author. If you share it, please give author credit and do not remove embedded links.
Computer code, if present in the article, is excluded from the above and licensed under GPLv3.
Citation
Cite this article as:
Wojnowski, Sylwester. "Recursive bubble sort algorithm in PHP." From sWWW - Code For The Web . https://swww.com.pl//main/index/recursive-bubble-sort-algorithm-in-php
Add Comment