<?php
Bubble sort, pick up the bubble sort content of Tifeng teacher video, personally think I understand this bubbling explanation is the easiest. Write down to learn from yourself!!!
$arr =array (3,2,-5,9,-15,7);//Specify an array $bar =count ($arr);
Determines the number of elements in the array $cnt = 0;
Define an intermediate variable
The main key code part of the bubble sort below
for ($i =0; $i < $bar; $i + +) {//outer for loop: $arr from the No. 0 element of this array.
for ($j = $i +1; $j < $bar; $j + +) {//Inner for loop: is the 1th element of the array starting from $arr, because the previous for loop has been evaluated from the No. 0 element of the array
if ($arr [$i]> $arr [$j]) {
$cnt = $arr [$i]; Assign a $arr[$i] to an intermediate variable $cnt
$arr [$i]= $arr [$j]; Assign a smaller value $arr[$j] to $arr[$i]
$arr [$j]= $cnt; Then assign the value of $cnt to $arr[$j]
//To determine the number of two for loops, if the left is greater than
//the number to the right, the left side is less than the right, then two number does not move
The core idea of the //bubble sort is to compare each element starting with the No. 0 array, followed by a different one, and the larger
In the back, the large number is thrown back, not more than two number of positions unchanged.
}
}
}
echo $i. " </br> ";
Print_r ($arr);
?>
-------------------------------Sub---------------------------------------boundary------------------------------------------------ ----Line------------------------------
Output Result:
0
1
2
3
4
5
Array ([0] = -15 [1] = 5 [2] = 2 [3] = 3 [4] = 7 [5] = 9)
Php bubble Sort, extract Tifeng teacher video bubble sort content!