The bubbling algorithm is a simple sort algorithm. It repeatedly visited the sequence to sort, comparing two elements at a time, and swapping them out if they were wrong in the order. The work of the sequence of visits is repeated until no more need to be exchanged, that is, the sequence is sorted. The algorithm is named because the smaller elements will slowly "float" through the switch to the top of the sequence.
function Bubblesort ($array) {
if (Empty ($array) | |!is_array ($ARRAY))
return false;
$len = count ($array)-1;
for ($i = $len; $i > 0; $i--) {
for ($j = 0; $j < $i; $j + +) {
if ($array [$j +1] < $array [$j]) {
$temp = $array [$j];
$array [$j] = $array [$j +1];
$array [$j +1] = $temp;
}
}
}
return $array;
}
Complexity of Time: O (n*n)
Bubble algorithm Improvement method one:
If no exchange occurs in one cycle, the data is already sorted out and the program jumps out.
function BubbleSort2 ($array)
{
if (Empty ($array) | |!is_array ($ARRAY))
return false;
$len = count ($array);
$ischange = false;
for ($i = $len-1; $i >0&&! $ischange; $i-)
{
$ischange = true;
for ($j =0; $j < $i; $j + +)
{
if ($array [$j +1] < $array [$j])
{
$temp = $array [$j];
$array [$j] = $array [$j + 1];
$array [$j + 1] = $temp;
$ischange =false;
}
}
}
return $array;
}
http://www.bkjia.com/PHPjc/477191.html www.bkjia.com true http://www.bkjia.com/PHPjc/477191.html techarticle The bubbling algorithm is a simple sort algorithm. It repeatedly visited the sequence to sort, comparing two elements at a time, and swapping them out if they were wrong in the order. To visit a series of ...