冒泡排序的实现
时间:2007-05-20 来源:liuxingyuyuni
/**
* @desc 冒泡算法 for java
* @auth BianJiang
*
* 纯碎学习之用
*/
class BobbleSort
{
public static void main(String[] args)
{
int i,j,k;
int[] num = {5, 4, 3, 2, 1};
for(i=1; inum.length; i++)
{
for(j=0; j=num.length -i -1; j++)
{
if(num[j] > num[j+1])
{
num[j] = num[j] + num[j+1]; //a = a + b
num[j+1]= num[j] - num[j+1]; //b = a - b
num[j] = num[j] - num[j+1]; //a = a - b
}
}
}
for(k=0; knum.length; k++)
{
System.out.println(num[k]);
}
}
}
/**
* @desc 冒泡算法 for php
* auther BianJiang
*/
?php
class BobbleSort
{
public $sort;
public function __construct($arr)
{
$this->sort = $arr;
}
public function Run()
{
for($i=0; $isizeof($this->sort); $i++)
{
for($j=0; $jsizeof($this->sort) - $i -1; $j++)
{
if($this->sort[$j] > $this->sort[$j+1])
{
$this->sort[$j] = $this->sort[$j] + $this->sort[$j+1]; //a = a + b
$this->sort[$j+1]= $this->sort[$j] - $this->sort[$j+1]; //b = a - b
$this->sort[$j] = $this->sort[$j] - $this->sort[$j+1]; //a = a - b
}
}
}
}
public function show()
{
echo "";
print_r($this->sort);
echo "";
}
}
$arr = array(5,4,3,2,1);
$bob = new BobbleSort($arr);
$bob->Run();
$bob->show();
?>
相关阅读 更多 +
排行榜 更多 +