不同方式实现冒泡

package study;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class temp
{
 public static void main(String[] args) throws IOException
 { 
// 下面相当于从键盘获得int [] a = new int[] {9,3,2,8,10,4,22};
// 第一种方法
  /* System.out.println("请输入五个整数:");
 
  int  a[] = new int [5]; 
  for (int i=0;i<5;i++)
  {
  InputStreamReader ir=new InputStreamReader(System.in);
  BufferedReader ln= new BufferedReader(ir);
  String s=ln.readLine();
  int  x =Integer.parseInt(s);
  a[i]=x;
  }   */
//第二种方法 
    System.out.println("请输入五个整数:");
 int a[] = new int[5];
 InputStreamReader ir = new InputStreamReader(System.in);
 BufferedReader ln = new BufferedReader(ir);
 String s = ln.readLine();
 //读取字符串,用逗号分隔
 String[] b=new String[5];
 b=s.split(",");
 for(int n=0;n<b.length;n++)
 {
  //给数组a赋值
  a[n]=Integer.valueOf(b[n]).intValue();
  System.out.print("a["+n+"]的值:"+a[n]+"; ");
 }
  System.out.println();
  
     for(int i = 0 ; i < a.length-1; i++){
          for(int j = 0 ; j < a.length-i-1; j++){
//          降序:   if(a[j]< a[j+1])  升序:if(a[j]>a[j+1])
              if(a[j]> a[j+1]){
                  int temp = a[j];
                  a[j] = a[j+1];
                  a[j+1] = temp;
                               }
                                                }
  
         System.out.println("第"+(i+1)+"轮冒泡:");
         for(int k = 0 ; k < a.length; k++){   
            System.out.print(a[k]+"    ");
                                           }
            System.out.println();
                                          }
 }
}

 

 


 

posted on 2020-05-31 08:52  half-acre  阅读(142)  评论(0编辑  收藏  举报