Php bubble sorting. After such a long time of contact with php, three sorting methods were used: Bubble sorting, fast sorting, and barrel sorting. today we will learn about bubble sorting: So what is bubble sorting, just as the gas in the river has been in contact with php for so long, three sorting methods have been used: Bubble sorting, fast sorting, and barrel sorting. let's learn about bubble sorting today:
So what is bubble sorting? just like bubbles in the river, one bubble emerges, and here is a number. its principle is repeated visit (traversal) the number of columns to be sorted. compare two adjacent numbers, move the large number to the right, and Traverse until all the numbers are sorted in ascending order. Compare the current maximum number each time. compare the remaining number in the next round and use two cycles to control the number of rounds in the outer loop and the elements in the comparison in the inner loop control:
Code on
/*** Bubble sort */$ list = Array (6, 8, 7, 2, 3, 4, 1); echo "before sorting"; print_r ($ list); function mao ($ arr) {for ($ I = 1, $ len = count ($ arr); $ I <$ len; ++ $ I) {// Number of outer loop arrays-1for ($ k = 0, $ klen = $ len-$ I; $ k <$ klen; ++ $ k) {// Inner Loop, compare two array elements, if ($ arr [$ k]> $ arr [$ k + 1]) {$ temp = $ arr [$ k]; $ arr [$ k] = $ arr [$ k + 1]; $ arr [$ k + 1] = $ temp ;}}return $ arr;} echo"
"; Print_r (mao ($ list ));
In the process of bubbling, the idea has been in the minds of others. in the process of Baidu, I saw another method and wrote it as well:
$ List = Array (6,8, 7,2, 3,4, 1); echo "before sorting"; print_r ($ list); function mao ($ arr) {for ($ I = 0, $ len = count ($ arr)-1; $ I <$ len; ++ $ I) {// The outer loop traverses the first layer and // The inner layer, add one on the outer layer to control the comparison of the two elements. for ($ k = $ I + 1; $ k <= $ len; ++ $ k) {if ($ arr [$ I]> $ arr [$ k]) {$ temp = $ arr [$ I]; $ arr [$ I] = $ arr [$ k]; $ arr [$ k] = $ temp; }}return $ arr;} echo"
"; Print_r (mao ($ list ));
In the process of writing, I admire the latter method. His thinking is very flexible, because the first method is based on our normal thinking. it is very straightforward, I felt very interesting in thinking,
Then what is bubble sorting, like the gas in the river...