The classic bubble sort method has been one of the sorts used by many programs, saying that the bubble sort method is more efficient than the PHP system function sort. This chapter does not discuss performance, so do not compare it to the system.
Bubble sort probably means to compare adjacent two numbers sequentially and then sort by size until the last two digits. Because the decimal is always pushed forward in the sort process, the large number is placed backward, which is the equivalent of a bubble going up, so called bubble sort. But in fact in the actual process can also be in accordance with their own needs in turn, the tree forward, the decimal place back.
The bubble sort method in <?php/** * PHP uses
the
///Advance declaration of an array
$arr = Array (12,45,28,30,88,67);
echo "original array";
Print_r ($arr);
echo "<br/>";
Bubble sort
Function Maopao ($arr) {
//For first-level traversal for
($i =0, $k =count ($arr); $i < $k; $i + +) {
//second-level traversal Compare each element in an array with the outer element
//The i+1 meaning here is for
($j = $i +1; $j < $k; $j + +) {
//inner-outer Layer two number comparison
if ($arr [$i ]< $arr [$j]) {
//First assign one of the arrays to a temporary variable
$temp = $arr [$j];
Swap position
$arr [$j] = $arr [$i];
Then assign the value from the temporary variable
$arr [$i] = $temp;
}}} Returns the sorted array return
$arr;
Direct print sort after array of
echo ' sort ';
Print_r (Maopao ($arr));
>
Execute results with the above code
Original array
Copy Code code as follows:
Array ([0] => [1] => [2] => [3] => [4] => [5] => 67)
After sorting
Copy Code code as follows:
Array ([0] => [1] => [2] => [3] => [4] => [5] => 12)
This is the Bubble Method example, simple! Without the difficulty of God horse.