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

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

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值