Sorting algorithms-Bubble sorting and Bubble Sorting

Source: Internet
Author: User

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:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.