|
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 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 sorting
- */
- $ 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-1
- For ($ k = 0, $ klen = $ len-$ I; $ k <$ klen; ++ $ k) {// an inner loop that compares 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) {// traverse the first layer of an outer loop
- // The inner layer loop. 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, |