冒泡算法复习

来源:互联网 发布:淘宝网账号限制登录 编辑:程序博客网 时间:2024/06/04 18:57

冒泡算法好多书上说是重点

现在来分析下

   1:  public class Arraysort {
   2:      public static void main(String[] args){
   3:          int arr[]={56,89,42,54,16,92,76,24,61};
   4:          int temp=0;        
   5:          for(int i=0;i<arr.length-1;i++){//不等于arr.length是最后一位不须再比
   6:              for(int j=0;j<arr.length-i-1;j++){
   7:                  if(arr[j]>arr[j+1]){
   8:                      temp=arr[j];
   9:                      arr[j]=arr[j+1];
  10:                      arr[j+1]=temp;
  11:                      
  12:                  }
  13:              }
  14:          }
  15:          System.out.print("数组中数字从小到大依次为:");
  16:          for(int i=0;i<arr.length;i++){
  17:          System.out.print(arr[i]+" ");
  18:          }
  19:      }
  20:  }
.csharpcode, .csharpcode pre{font-size: small;color: black;font-family: consolas, "Courier New", courier, monospace;background-color: #ffffff;/*white-space: pre;*/}.csharpcode pre { margin: 0em; }.csharpcode .rem { color: #008000; }.csharpcode .kwrd { color: #0000ff; }.csharpcode .str { color: #006080; }.csharpcode .op { color: #0000c0; }.csharpcode .preproc { color: #cc6633; }.csharpcode .asp { background-color: #ffff00; }.csharpcode .html { color: #800000; }.csharpcode .attr { color: #ff0000; }.csharpcode .alt {background-color: #f4f4f4;width: 100%;margin: 0em;}.csharpcode .lnum { color: #606060; }

较难理解是两层循环都 是从0开始的,如果我们把0改成1来分析下,

就以5个数来从小到大分析,第一个和第二个比,如果第一个比第二个大则互换,小则不变,第二个和第三个比,第三个和第四个比,依次。

1 2 3 4 5

第几次循环 比较次数 1 4 2 3 3 2 4 1(第一个和第二个比)

此时循环代码如下,5个数,循环4次,比较次数为5-第几次循环数

   1:  for(int i=1;i<length;i++){
   2:      for(int j=1;j<length-i;j++){
   3:          if(arr[n]>a[n+1]){   //从小到大排,a[n]>a[n+1]互换
   4:              temp=arr[n];
   5:              arr[n]=arr[n+1];
   6:              arr[n+1]=temp;
   7:          }
   8:      }
   9:  }
.csharpcode, .csharpcode pre{font-size: small;color: black;font-family: consolas, "Courier New", courier, monospace;background-color: #ffffff;/*white-space: pre;*/}.csharpcode pre { margin: 0em; }.csharpcode .rem { color: #008000; }.csharpcode .kwrd { color: #0000ff; }.csharpcode .str { color: #006080; }.csharpcode .op { color: #0000c0; }.csharpcode .preproc { color: #cc6633; }.csharpcode .asp { background-color: #ffff00; }.csharpcode .html { color: #800000; }.csharpcode .attr { color: #ff0000; }.csharpcode .alt {background-color: #f4f4f4;width: 100%;margin: 0em;}.csharpcode .lnum { color: #606060; }
0 0
原创粉丝点击