JAVA手記(2005.12.29)-冒泡排序

import java.io.*;

class Swap//用於交換的類
{
   void swap(int x,int y)
   {
       int temp;
       temp = x;
       x = y;
       y = temp;
   } 
}

class BubbleSort//冒泡算法
{
 
 void bubsort(int[] a)
 {
  boolean flag;//設置標誌位
  int j;
  Swap sw = new Swap();
  for(int i=0;i<(a.length-1);i++)
  {
   for(j=0;j<(a.length-1-i);j++);
   {
    if(a[j]>a[j+1])
    sw.swap(a[j],a[j+1]);
    /*{
     int temp = a[j];
     a[j] = a[j+1];
     a[j+1] = temp;
    }*/
       flag = false;
   }
  if(flag = true) return;
  }
  return;
 }
}


class TestBubble//main()函數
{
 public static void main(String[] args) throws IOException
 {
  
  BufferedReader br = new BufferedReader(new InputStreamReader(System.in));//鍵盤讀入
  //String str = br.readLine();
  //int r = Integer.parseInt(str);
  System.out.println("Enter the size:");
  String str1 = br.readLine();
  int size = Integer.parseInt(str1);//讀入的數據定義爲數組的大小
  int[] a = new int[size];//初始化大小爲size的數組
  
  System.out.println("Input "+size+" numbers:");//用鍵盤輸入數組的每個元素
  for(int i=0;i<size;i++)
    {
     String str2 = br.readLine();//注意這裏,沒有必要在重複定義br,但這裏的str2一定要定義
     int val = Integer.parseInt(str2);//讀入的值賦給數組的每個元素
     a[i] = val;
    }
  System.out.println("The array is:");//打印
  for(int i=0;i<size;i++)
     System.out.println("a["+i+"]="+a[i]);
  
  BubbleSort bs = new BubbleSort();//創建對象
      bs.bubsort(a);                                  //調用對象方法
  System.out.println("After sorted:");  //打印冒泡排序好了的數組
 
  for(int i=0;i<size;i++)
  System.out.println("a["+i+"]="+a[i]);    
 }
}

編譯階段沒有出現錯誤,但運行時候報錯:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章