zoukankan      html  css  js  c++  java
  • [php]数据结构&算法(PHP描述) 冒泡排序 bubble sort

     1 <?php
    2 /**
    3 * 冒泡排序 bubble sort
    4 *
    5 * 原理:多次循环进行比较,每次比较时将最大数移动到最上面。每次循环时,找出剩余变量里的最大值,然后减小查询范围。这样经过多次循环以后,就完成了对这个数组的排序
    6 */
    7 function sort_bubble($list)
    8 {
    9 $len=count($list);
    10 if(empty($len)) return$list;
    11 $is_change=false;
    12
    13 for($i=0;$i<$len; $i++)
    14 {
    15 for($j=$i+1; $j<$len; $j++)
    16 {
    17 $flag='';
    18 if($list[$i] >$list[$j]) // 从小到大
    19 //if($list[$i] < $list[$j]) // 从大到小
    20 {
    21 $tmp=$list[$i];
    22 $list[$i] =$list[$j];
    23 $list[$j] =$tmp;
    24
    25 $is_change=true; // 进行了交换
    26
    27 $flag=" change";
    28 }
    29 echoimplode(',',$list).$flag."<br/>";
    30 }
    31
    32 if(!$is_change) { // 如果第一轮没有发生值交换的话,说明传入的数组是顺序,不需要再进行排序了
    33 break;
    34 }
    35
    36 echo"-------------------------<br/>";
    37 }
    38 return$list;
    39 }
    40
    41 $list=array(4,3,2,1,5,7,3,7);
    42 $list= sort_bubble($list);

     根据 @楚风 提示修改了一下 如果第一轮没有发生值交换的话 跳出; 2011-07-26

  • 相关阅读:
    94. Binary Tree Inorder Traversal
    101. Symmetric Tree
    38. Count and Say
    28. Implement strStr()
    实训团队心得(1)
    探索性测试入门
    LC.278. First Bad Version
    Search in Unknown Sized Sorted Array
    LC.88. Merge Sorted Array
    LC.283.Move Zeroes
  • 原文地址:https://www.cnblogs.com/bluefrog/p/2101523.html
Copyright © 2011-2022 走看看