php bubble sort

WBOY
Release: 2016-07-25 09:13:07
Original
928 people have browsed it

I have been in contact with PHP for so long, and I have only used three kinds of sorting, bubble sorting, quick sorting, and barrel sorting. Let’s learn bubble sorting today:

So what is bubble sorting? Just like bubbles in a river, bubbles surface one by one, and here are numbers one by one. Its principle is to repeatedly visit (traverse) the sequence to be sorted and compare adjacent ones. Of the two numbers, move the larger number to the right, and then traverse until all numbers complete the order from small to large. Each time the current maximum is compared, the remaining numbers are compared in the next round. Two loops are used to do it. The outer loop controls the number of rounds, and the inner loop controls the elements of comparison:

Upload the code

  1. /**
  2. * Bubble sort
  3. */
  4. $list = Array(6,8,7,2,3,4,1);
  5. echo "before sorting";
  6. print_r($list);
  7. function mao ($arr){
  8. for($i=1,$len=count($arr);$i<$len;++$i){ // Number of outer loop arrays-1
  9. for($k= 0,$klen=$len-$i;$k<$klen;++$k){ // Inner loop, compare two array elements
  10. if($arr[$k]>$arr[$k +1]){
  11. $temp = $arr[$k];
  12. $arr[$k] = $arr[$k+1];
  13. $arr[$k+1] = $temp;
  14. }
  15. }
  16. }
  17. return $arr;
  18. }
  19. echo "
    After sorting";
  20. print_r(mao($list));
Copy code

In the process of bubbling, my ideas have been in other people’s thoughts. In the process of Baidu, I saw another method and thought it was good, so I wrote it:

  1. $list = Array(6,8,7,2,3,4,1);
  2. echo "before sorting";
  3. print_r($list);
  4. function mao($arr){
  5. for($ i=0,$len=count($arr)-1;$i<$len;++$i){ // The outer loop performs the first level traversal
  6. // The inner loop adds on the basis of the outer layer 1. To control the comparison of two elements
  7. for($k=$i+1;$k<=$len;++$k){
  8. if($arr[$i]>$arr[$k] ){
  9. $temp = $arr[$i];
  10. $arr[$i] = $arr[$k];
  11. $arr[$k] = $temp;
  12. }
  13. }
  14. }
  15. return $arr;
  16. }
  17. echo "
    After sorting";
  18. print_r(mao($list));
Copy code

 

During the writing process, I admired the latter way of writing very much. His thinking is very flexible, because the first way of writing is based on our normal thinking. It is very straightforward and I feel that the thinking is very interesting.



Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!