Home  >  Article  >  Backend Development  >  Sorting Algorithm Bubble Algorithm_PHP Tutorial

Sorting Algorithm Bubble Algorithm_PHP Tutorial

WBOY
WBOYOriginal
2016-07-14 10:12:23976browse

Bubble algorithm is a simple sorting algorithm. It repeatedly walks through the sequence to be sorted, comparing two elements at a time and swapping them if they are in the wrong order. The work of visiting the array is repeated until no more exchanges are needed, which means that the array has been sorted. The name of this algorithm comes from the fact that smaller elements will slowly "float" to the top of the array through swapping.


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;
}

Time complexity: O(n*n)


Bubble algorithm improvement method one:

If no exchange occurs in a certain loop, it means that the data has been sorted and the program will jump out directly.

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;
}

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/477191.htmlTechArticleThe bubble algorithm is a simple sorting algorithm. It repeatedly walks through the sequence to be sorted, comparing two elements at a time and swapping them if they are in the wrong order. Visiting the sequence...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn