The bubble algorithm of sorting algorithm _php tutorial

Source: Internet
Author: User
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 ...

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.