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]);
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]);
}
}
編譯階段沒有出現錯誤,但運作時候報錯: