Sorting algorithms-Bubble sorting and Bubble Sorting
This section describes the basic idea of Bubble Sorting in big talk Data Structure: Compares the keywords of Adjacent Elements in two or two pairs. If the reverse order is used, it is exchanged until there is no reverse order record. That is, the two adjacent elements are compared. If the previous value is greater than the next one (or the previous value is smaller than the next one), the order is exchanged, the final result is the sorting from small to large (or from large to small.
Of course, php has very powerful sorting functions, such as sort and asort. Therefore, you do not need to write the sorting function yourself when using php. Here, you just use php to implement the idea of Bubble sorting.
1 <? Php 2 shortde_once '. /header. php '; 3 4 $ bub = array (9, 5, 8, 3, 4, 6, 1, 2, 7,); 5 $ sortarr = $ asortarr = $ bub; 6 7 // bubble sort 8 $ flag = true; 9 for ($ I = 0; $ I <count ($ bub)-1 & $ flag; $ I ++) {// when the flag is false, the sorting is completed, and 10 11 $ flag = false is not cyclically followed; 12 for ($ j = count ($ bub)-2; $ j >=$ I; $ j --) {13 14 if ($ bub [$ j]> $ bub [$ j + 1]) {// The number above is greater than the number below, and the switching position is 15 16 $ temp = $ bub [$ j]; 17 $ bub [$ j] = $ bub [$ j + 1]; 18 $ bub [$ j + 1] = $ temp; 19 $ flag = true; 20 } 21} 22} 23 // sort the array units in descending order of 24 sort ($ sortarr ); 25 // re-sort the array and maintain the index relationship 26 asort ($ asortarr); 27 28 echo 'bubble: '; 29 echo' <pre> '; 30 var_dump ($ bub); 31 32 echo 'sort: '; 33 echo' <pre> '; 34 var_dump ($ sortarr); 35 36 echo 'asort :'; 37 echo '<pre>'; 38 var_dump ($ asortarr); 39?>
Code output result: