基本思想
两两进行比较,左边的数大于右边的数,则进行交换。
代码示例
创建一个冒泡排序类Bubble,实例化对象时传递要排序的数组$arr,然后调用bubbleSort进行排序。
//冒泡排序类
class Bubble{
protected $data;
protected $desc;
function __Construct($arr,$desc = true){
$this->data = $arr;
$this->desc = $desc;
}
private function swap($i,$j){
$temp = $this->data[$i];
$this->data[$i] = $this->data[$j];
$this->data[$j] = $temp;
}
public function bubbleSort(){
$len = count($this->data);
for($i=0;$i<$len-1;$i++){
for($j=$i+1;$j<$len;$j++){
if($this->desc)
{
if($this->data[$i]>$this->data[$j])
{
$this->swap($i,$j);
}
}
else
{
if($this->data[$i]<$this->data[$j])
{
$this->swap($i,$j);
}
}
}
}
}
public function getSortedData(){
return $this->data;
}
}
//客户端示例
$arr = array(1,4,2,6,3,8);
$sort = new Bubble($arr);//new Bubble($arr,false);倒序
$sort->bubbleSort();
var_dump($sort->getSortedData());
算法说明
时间复杂度:n^2
实现简单,对于数据规模较小的数组可采用此排序算法。