随机生成20-9999的整数,冒泡排序

package com.stream.ch10; 

/*

 * 随机生成15个20--9999之间的整数

 * 将这15个数写入文件file.txt

 * 读取file.txt中的15个数,进行冒泡排序

 * 显示排序结果

 *  

 */ 

import java.util.Random;

import java.io.*;

public class Random_Bubble

{

  static void sort1(int []a)

  {

    int i,j;

    for(i=0;i<a.length;i++)

    {

      for(j=0;j<a.length-i-1;j++)

      {

        if(a[j]>a[j+1])

        {

          int temp;

          temp=a[j];

          a[j]=a[j+1];

          a[j+1]=temp;

        }

      }

    }

  }

  public static void main(String []args) throws IOException

  {

    Random rand=new Random();

    BufferedWriter output=new BufferedWriter(new FileWriter("/Users/sx_dqbsina.com/file.txt"));  //output对象指向file.txt

    int []num1=new int[15];  //声明数组,15个元素

    for(int i=0;i<num1.length;i++)

    {

      num1[i]=20+rand.nextInt(9979);  //生成15个20--9999的随机数,存到数组num1中

      output.write(num1[i]+"");   //将随机数写入output指向的文件,即file.txt

      output.newLine();   //写完一个数,换行

    }

    output.close();

    BufferedReader input=new BufferedReader(new FileReader("/Users/sx_dqbsina.com/file.txt"));  //input对象指向file.txt文件

    int []num2=new int[15];

    for(int i=0;i<num2.length;i++)

    {

      num2[i]=Integer.parseInt(input.readLine());  //循环15次,将input指向的file.txt中的数读到num2数组中

    }

    input.close();

    sort1(num2);

    System.out.println("排序结果:");

    for(int i=0;i<num2.length;i++)

    {

      if(i%5==0)

        System.out.println();         //每5个数一行

      System.out.print(num2[i]+ "     ");

    }

  }

}

运行结果:

原文地址:https://www.cnblogs.com/duanqibo/p/11201628.html