JAVA手记(2005.12.29)-冒泡排序

    技术2022-05-11  121

    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]);      }}

    编译阶段没有出现错误,但运行时候报错:


    最新回复(0)