Home >Backend Development >PHP Tutorial >Several examples of bubble sorting implemented in PHP_PHP tutorial
PHP bubble sorting is to implement data exchange and then find the largest and smallest, and finally exchange the positions for sorting. This is the sorting method we have used most before.
The basic concept of bubble sort (BubbleSort) is:
Compare two adjacent numbers in sequence, putting the decimal in front and the large number in the back. That is, in the first pass: first compare the first and second numbers, put the decimal first and the large number last. Then compare the second number and the third number, put the decimal in front and the large number in the back, and continue like this until comparing the last two numbers, put the decimal in front and the large number in the back. This is the end of the first trip, leaving the largest number at the end. In the second pass: still start the comparison from the first pair of numbers (because it may be due to the exchange of the second number and the third number that the first number is no longer smaller than the second number), put the decimal first, and the large number After placing it, the comparison is continued until the second to last number (the first to last position is already the largest). At the end of the second pass, a new maximum number is obtained at the second to last position (in fact, it is the largest number in the entire sequence). The second largest number). Continue like this and repeat the above process until the sorting is finally completed.
Example 1, simple implementation of bubble sort
The code is as follows
|
Copy code
|
||||
$arr = array(12,45,89,3,24,55,223,76,22,11,89,2,4,5,28,112,20,434,23,65,65,765,6,8,23,5,33,553 ,45,423,64,77,84,23); $tmp; for($i=0;$i $tmp = $arr[$j]; $arr[$j] = $arr[$j+1]; $arr[$j+1] = $tmp; } } |
The code is as follows | Copy code |
//Bubble sort method function bubblesort(&$arr){ //Define a variable to save the exchanged value $temp =0; for($i=0;$i // If the previous number is greater than the subsequent number, then they exchange $ tmp = $ 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); //Arrays are passed by value, so adding an & symbol when passing is address passing and changing external variables ?> |