Home >Backend Development >PHP Tutorial >Implement bubble sorting (from small to large) using PHP

Implement bubble sorting (from small to large) using PHP

WBOY
WBOYOriginal
2016-07-23 08:54:521692browse
  1. //Array element values ​​are sorted from small to large
  2. $arr=array(1,42,0,3,15,7,19,26);
  3. //Define an intermediate variable
  4. $ temp=0;
  5. //Number of outer loops
  6. for($i=0;$i //Two arrays adjacent to the right between the inner layers Compare the element values
  7. for($j=0;$j //When the value of the next array element is greater than the original value of the previous array
  8. if($arr [$j]>$arr[$j+1]){
  9. //Array element exchange
  10. $temp=$arr[$j];
  11. $arr[$j]=$arr[$j+1];
  12. $arr[$j+1]=$temp;
  13. }
  14. }
  15. //The number of times the outer array loop is ---count($arr)-1
  16. //The reason for -1 (array element value comparison It is two comparisons
  17. //For example, three array elements are compared twice
  18. echo "This is the result of the ".($i+1)."th comparison";
  19. echo "
    ";
  20. print_r($arr);
  21. echo "
    ";
  22. }
  23. echo "
    ";
  24. echo "
    ";
  25. print_r($arr) ;
  26. echo "
    "; 
  27. ?>
Copy code

PHP


Statement:
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