Bubbling sort is very easy to understand and implement, with an example from small to large:
Set the array length to n.
1. Compare the next two data, if the previous data is larger than the data, two data will be exchanged.
2. So that the No. 0 data of the array to N-1 data after one traversal, the largest one of the data is "sink" to the N-1 position of the array.
3. N=n-1, if N is not 0, repeat the previous two steps, otherwise the sort is complete.
Programme one:
1 functionBubble1_sort ($array){2 $count=Count($array);3 if($count<=1){4 return $array;5 }6 for($i= 0;$i<$count;$i++){7 for($j= 0;$j<$count;$j++){8 if($array[$i]<$array[$j]){9 $temp=$array[$i];Ten $array[$i]=$array[$j]; One $array[$j]=$temp; A } - } - } the return $array; -}
Scenario Two:
1 functionBubble2_sort ($array){2 $count=Count($array);3 if($count<=1){4 return $array;5 }6 7 for($i= 0;$i<$count;$i++){8 for($j= 1;$j<$count-$i;$j++){9 if($array[$j-1]>$array[$j]){Ten $temp=$array[$j-1]; One $array[$j-1]=$array[$j]; A $array[$j]=$temp; - } - } the } - return $array; -}
Programme III:
Sets a flag that is true if the interchange occurred, otherwise false. Obviously if there was a trip without an exchange, the description sort has been completed.
1 functionBubble3_sort ($array){2 $count=Count($array);3 if($count<=1){4 return $array;5 }6 $flag=true;7 $j=$count;8 while($flag){9 $flag=false;Ten for($i= 1;$i<$j;$i++){ One if($array[$i-1]>$array[$i]){ A $temp=$array[$i-1]; - $array[$i-1]=$array[$i]; - $array[$i]=$temp; the $flag=true; - } - } - $j--; + - } + return $array; A at}
Programme IV:
If there are 100 number of arrays, only the first 10 unordered, and the next 90 are all ordered and are greater than the preceding 10 digits, then after the initial traversal, the position of the last interchange must be less than 10, and the position after the data must be ordered, record the position, The second time, just walk from the array head to this position.
1 functionBubble4_sort ($array){2 $count=Count($array);3 if($count<=1){4 return $array;5 }6 $flag=$count;7 while($flag>0){8 $k=$flag;9 $flag=0;Ten for($j= 1;$j<$k;$j++){ One if($array[$j-1]>$array[$j]){ A $temp=$array[$j-1]; - $array[$j-1]=$array[$j]; - $array[$j]=$temp; the $flag=$j; - } - } - } + return $array; -}
Programme V:
1 functionBubble_sort ($array){2 $count=Count($array);3 if($count<=1){4 return $array;5 }6 for($i=$count-1;$i>0;$i--){7 $flag=false;8 for($j= 0;$j<$count;$j++){9 if($array[$j]>$array[$j+1]){Ten $temp=$array[$j]; One $array[$j]=$array[$j+1]; A $array[$j+1]=$temp; - $flag=true; - } the } - if(!$flag) - Break; - } + return $array; -}
PHP Implementation Bubble sort