PHP data structure algorithm describes bubble sort bubble sort

  • 2020-05-09 18:17:42
  • OfStack

 
<?php 
/** 
*  Bubble sort  bubble sort 
* 
*  The principle of : Loop the comparison multiple times, moving the maximum number to the top each time. Each time you loop, find the maximum value in the remaining variables, and then reduce the query range. After many cycles, you have sorted the array  
*/ 
function sort_bubble($list) 
{ 
$len = count($list); 
if(empty($len)) return $list; 

for($i = 0;$i < $len; $i++) 
{ 
for($j = $i + 1; $j < $len; $j++) 
{ 
$flag = ''; 
if($list[$i] > $list[$j]) //  Since the childhood  
//if($list[$i] < $list[$j]) //  From big to small  
{ 
$tmp = $list[$i]; 
$list[$i] = $list[$j]; 
$list[$j] = $tmp; 

$flag = " change"; 
} 
echo implode(',',$list).$flag."<br/>"; 
} 
echo "-------------------------<br/>"; 
} 
return $list; 
} 

$list = array(4,3,2,1,5,7,3,7); 
$list = sort_bubble($list); 

Related articles: