Home  >  Article  >  Backend Development  >  PHP implementation of bubble sort_PHP tutorial

PHP implementation of bubble sort_PHP tutorial

WBOY
WBOYOriginal
2016-07-14 10:11:181009browse

[php]
/*
*Bubble sorting is a brute force method with a time complexity of N squared. It can be improved: if the positions of elements are not exchanged after comparing the list, then the list has been sorted and the algorithm stops
*/

function bubble_sort($arr){
$len=count($arr);
for($i=0;$i<$len-1;$i++){
for ($j=0; $j < $len-i-1; $j++) {
If($arr[$j+1]<$arr[$j]){
                    $tmp=$arr[$j];
                    $arr[$j]=$arr[$j+1];
                     $arr[$j+1]=$tmp;
                                                                                                                                               } 
}  
Return $arr;
}
$arr=array(3,8,2,5,6);
$res=bubble_sort($arr);
print_r($res);
?>

/*
*Bubble sorting is a brute force method with a time complexity of N squared. It can be improved: if the positions of elements are not exchanged after comparing the list, then the list has been sorted and the algorithm stops
*/

function bubble_sort($arr){

$len=count($arr);
for($i=0;$i<$len-1;$i++){
for ($j=0; $j < $len-i-1; $j++) {
if($arr[$j+1]<$arr[$j]){
$tmp=$arr[$j];
$arr[$j]=$arr[$j+1];
$arr[$j+1]=$tmp;
}
}
}
return $arr;
}
$arr=array(3,8,2,5,6);
$res=bubble_sort($arr);
print_r($res);
?>

http://www.bkjia.com/PHPjc/477344.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/477344.htmlTechArticle[php] ?php /* *Bubble sorting is a brute force method, and the time complexity is N squared. An improvement can be made: If the positions of elements are not exchanged after comparing the lists, then the list has...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn