1, first we have to figure out what is bubble sort, do not understand the principle of bubble sort, we can not write code.
The basic concept of bubble sort (bubblesort) is to compare the number of adjacent two digits, place the decimal number in the front, and put the large numbers behind. On the first trip: first compare the 1th and 2nd numbers, put the decimal number before the big number put. Then compare the 2nd and 3rd numbers, put the decimal places before the large number, so continue until the last two, the number of decimal places before the large number of put. At the end of the first trip, the largest number was put to the end. On the second trip: the comparison is still starting from the first logarithm (since the exchange of the 2nd and 3rd numbers is possible, so that the 1th number is no longer less than the 2nd number, the decimal place before, after the large number, has been compared to the penultimate number (the first in the last position is already the largest), the second end, To get a new maximum number (in fact, the second largest number in the whole series) in the penultimate position. So go on, repeat the process until you finish sorting.
PHP Implementation code:
<?php
//bubble Sort method
function Bubblesort (& $arr) {
//define a variable to hold the value of the Exchange
$temp =0;
For ($i =0 $i <count ($arr); $i + +) {for
($j =0; $j <count ($arr)-$i-1; $j + +) {
if ($arr [$j]> $arr [$j +1]) {
//If the previous number is greater than the one behind it, they will exchange
$temp = $arr [$j];
$arr [$j]= $arr [$j +1];
$arr [$j +1]= $temp;
}
}}} $arr =array (100,99,200,5,-4,6,-7);
Bubblesort ($arr);
Print_r ($arr); The array is a value pass, so the time to pass the & symbol is the address transfer, change the external variable
?>
Above this PHP implementation bubble sort of simple example is small to share all the content of everyone, hope to give you a reference, but also hope that we support cloud habitat community.