php实现冒泡排序、双向冒泡排序算法 1
/**
* 数据结构与算法(php实现) - 冒泡排序(bubble sort)。
*
* @author 创想编程(topphp.org)
* @copyright copyright (c) 2013 创想编程(topphp.org) all rights reserved
* @license http://www.opensource.org/licenses/mit-license.php mit license
* @version 1.0.0 - build20130608
*/
class bubblesort {
/**
* 冒泡排序。
*
* @var integer
*/
const sort_normal = 1;
/**
* 双向冒泡排序。
*
* @var integer
*/
const sort_duplex = 2;
/**
* 需要排序的数据数组。
*
* @var array
*/
private $data;
/**
* 数据数组的长度。
*
* @var integer
*/
private $size;
/**
* 数据数组是否已排序。
*
* @var boolean
*/
private $done;
/**
* 构造方法 - 初始化数据。
*
* @param array $data 需要排序的数据数组。
*/
public function __construct(array $data) {
$this->data = $data;
$this->size = count($this->data);
$this->done = false;
}
/**
* 交换数据数组中两个元素的位置。
*
* @param integer $x 元素在数组中的索引。
* @param integer $y 元素在数组中的索引。
*/
private function swap($x, $y) {
$temp = $this->data[$x];
$this->data[$x] = $this->data[$y];
$this->data[$y] = $temp;
}
/**
* 冒泡排序。
*/
private function sort() {
$this->done = true;
for ($i = 1; $i size; ++$i) {
// 记录交换数据的次数。
$swap = 0;
for ($j = $this->size - 1; $j > $i - 1; --$j) {
if ($this->data[$j] data[$j - 1]) {
$this->swap($j - 1, $j);
++$swap;
}
}
// 若交换数据的次数为0,说明数据数组已有序,不必再进行排序。
if (0 === $swap) {
break ;
}
}
}
/**
* 双向冒泡排序。
*/
private function duplexsort() {
$this->done = true;
for ($i = 1; $i size / 2); ++$i) {
// 记录交换数据的次数。
$swap = 0;
for ($j = $this->size - 1, $k = $i - 1;
$j > $i - 1 && $k size - 1; --$j, ++$k) {
if ($this->data[$j] data[$j - 1]) {
$this->swap($j - 1, $j);
++$swap;
}
if ($this->data[$k] > $this->data[$k + 1]) {
$this->swap($k, $k + 1);
++$swap;
}
}
// 若交换数据的次数为0,说明数据数组已有序,不必再进行排序。
if (0 === $swap) {
break;
}
}
}
/**
* 获取排序后的数据数组。
*
* @param integer $sort 排序算法:sort_normal为冒泡排序;sort_duplex为双向冒泡排序。
* @return array 返回排序后的数据数组。
*/
public function getresult($sort = self::sort_normal) {
// 若已排序则无需再进行排序,直接返回排序好的数据数组。
if ($this->done) {
return $this->data;
}
switch ($sort) {
case self::sort_duplex:
$this->duplexsort();
break;
case self::sort_normal:
default:
$this->sort();
break;
}
return $this->data;
}
}
?>
示例代码 1
2
3
4 getresult(bubblesort::sort_duplex), true), '
';
?>
http://www.bkjia.com/phpjc/477265.htmlwww.bkjia.comtruehttp://www.bkjia.com/phpjc/477265.htmltecharticle冒泡排序(bubble sort),是一种较简单的、稳定的排序算法。冒泡排序算法步骤:比较相邻的元素,如果第一个比第二个大,就交换他们两...
