冒泡排序是一种常见的排序算法,本题要求用冒泡排序算法对一组数字进行从小到大排序
输入:输入的是一行数字,就是我们需要排序的数字
输出:输出是从小到大排序好的数字,数字之间用空格分开
样例输入
2 1 5 8 21 12
样例输出
1 2 5 8 12 21
代码实现:
package 排序;
import java.util.Scanner;
public class maopao {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int [] arr = new int[6];
for (int i=0;i<arr.length;i++) {
arr[i] = input.nextInt();
}
bubbleSort(arr);
printArray(arr);
}
public static void bubbleSort(int[] arr) {
if (arr == null || arr.length < 2) {
return;
}
for (int e = arr.length - 1; e > 0; e--) {
for (int i = 0; i < e; i++) {
if (arr[i] > arr[i + 1]) {
swap(arr, i, i + 1);
}
}
}
}
public static void swap(int[] arr, int i, int j) {
arr[i] = arr[i] ^ arr[j];
arr[j] = arr[i] ^ arr[j];
arr[i] = arr[i] ^ arr[j];
}
public static void printArray(int[] arr) {
if (arr == null) {
return;
}
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
}
}
修改后通过的代码:
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String line = sc.nextLine();
String[] split = line.split(" ");
List list = Arrays.asList(split);
for (int i = 0; i < list.size(); i++) {
String s = (String) list.get(i);
if ("".equals(s)) {
list.remove(i);
}
}
int[] ints = new int[list.size()];
for (int i = 0; i < ints.length; i++) {
ints[i] = Integer.parseInt(list.get(i)+"");
}
for (int i = 0; i < ints.length; i++) {
for (int j = 1; j < ints.length - i; j++) {
int temp = ints[j - 1];
if (temp > ints[j]) {
ints[j - 1] = ints[j];
ints[j] = temp;
}
}
}
for (int i = 0; i < ints.length - 1; i++) {
int anInt = ints[i];
System.out.print(String.format("%d ", anInt));
}
System.out.println(ints[ints.length - 1]);
}
}