Home > php教程 > php手册 > 冒泡排序的PHP实现

冒泡排序的PHP实现

WBOY
Release: 2016-06-13 10:57:34
Original
1185 people have browsed it

[php]
/* 
*冒泡排序属于蛮力法,时间复杂度为N的平方,可以做一下改进:如果对列表比较一遍之后没有交换元素的位置,那么这个表已经排好序了,算法停止
*/ 
 
function bubble_sort($arr){ 
    $len=count($arr); 
    for($i=0;$i         for ($j=0; $j             if($arr[$j+1]                 $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); 
?> 

/*
*冒泡排序属于蛮力法,时间复杂度为N的平方,可以做一下改进:如果对列表比较一遍之后没有交换元素的位置,那么这个表已经排好序了,算法停止
*/

function bubble_sort($arr){
 $len=count($arr);
 for($i=0;$i   for ($j=0; $j    if($arr[$j+1]     $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);
?>

 

source:php.cn
Statement of this Website
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
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template