Java数组之冒泡排序

import java.util.Scanner;

public class BubbleSort {
    public static void main(String[] args) {
        System.out.print("please input numbers count:");
        Scanner scan = new Scanner(System.in);
        int count = scan.nextInt();
        int[] numbers = new int[count];
        System.out.println("please input numbers:");
        for (int i = 0; i < numbers.length; i++) {

            numbers[i] = scan.nextInt();
        }

        boolean sorted = true;
        for (int lun = 0; lun < numbers.length - 1; lun++) {
            for (int i = 0; i < numbers.length - 1 - lun; i++) {
                if(numbers[i] > numbers[i+1]){
                    int temp = numbers[i];
                    numbers[i] = numbers[i+1];
                    numbers[i+1] = temp;
                    sorted = false;
                }
            }

            if(sorted){
                break;
            }
        }

//        int lastIdx =  numbers.length - 1;
//        while (lastIdx > 0){
//            for (int i = 0; i < lastIdx; i++) {
//                if(numbers[i] > numbers[i+1]){
//                    int temp = numbers[i];
//                    numbers[i] = numbers[i+1];
//                    numbers[i+1] = temp;
//                }
//            }
//             lastIdx--;
//        }

        System.out.println("the sorted numbers are:");
        for (int number : numbers) {
            System.out.print(number + " ");
        }
    }

}

//    please input numbers count:11
//    please input numbers:
//    34
//    54
//    3
//    2
//    65
//    7
//    34
//    5
//    76
//    34
//    67
//    the sorted numbers are:
//    2 3 5 7 34 34 34 54 65 67 76
posted @ 2023-05-17 06:12  无风听海  阅读(13)  评论(0编辑  收藏  举报