JAVA读取一行输入数字,进行简单排序

来源:互联网 发布:java构造方法语法要求 编辑:程序博客网 时间:2024/06/09 19:19

冒泡排序是一种常见的排序算法,本题要求用冒泡排序算法对一组数字进行从小到大排序

输入:输入的是一行数字,就是我们需要排序的数字

输出:输出是从小到大排序好的数字,数字之间用空格分开

样例输入

2 1 5 8 21 12

样例输出

1 2 5 8 12 21
public static void main(String[] args) {Scanner sc = new Scanner(System.in);String s = sc.nextLine();//将用户输入的一整行字符串赋给sString[] c = s.split("\\s+");//用空格将其分割成字符串数组int size = c.length;int[] b =new int[size];for (int m = 0; m < b.length; m++) {b[m] = Integer.parseInt(c[m]);//讲字符串数组转换成int数组}int temp=0;for (int i = 0; i < b.length; i++) {for (int j = 0; j < b.length-i-1; j++) {if(b[j]>b[j+1]){temp=b[j];b[j]=b[j+1];b[j+1]=temp;}}}for(int n = 0; n < b.length ; n++){System.out.print(b[n]);System.out.print(' ');}sc.close(); }


1 0