public class Sort {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("请您输入整数的个数:");
int count = input.nextInt();
int[] array = new int[count];
for (int i = 0; i < count; i++) {
System.out.println("请输入第" + (i + 1) + "个整数:");
array[i] = input.nextInt();
}
input.close();
System.out.println("========================");
BubbleSort(array);
System.out.println("========================");
selectSort(array);
}
// 冒泡排序从大到小排序
private static void BubbleSort(int[] array) {
// 外层循环,是需要进行比较的轮数,
for (int i = 0; i < array.length - 1; i++) {
// 内层循环,是每一轮中进行的两两比较
for (int j = 0; j < array.length - 1 - i; j++) {
if (array[j] < array[j + 1]) {
int temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
System.out.println("第" + (i + 1) + "轮冒泡排序后的数组为: " + Arrays.toString(array));
}
}
// 选择排序从小到大
private static void selectSort(int[] array) {
// 外层循环,是需要进行比较的轮数,
for (int i = 0; i < array.length - 1; i++) {
// 内层循环,是每一轮中进行的两两比较
for (int j = i + 1; j < array.length; j++) {
if (array[i] > array[j]) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
System.out.println("第" + (i + 1) + "轮选择排序后的数组为: " + Arrays.toString(array));
}
}
}
来源:oschina
链接:https://my.oschina.net/u/4459974/blog/3175484