冒泡/选择排序Demo

冒泡排序

    public static void main(String[] args) throws Exception {
        int[] numbers = ArrayTools.getRandomInts2(7, -9, 9);
        ArrayTools.printInts(numbers);
        bubbleSort(numbers);
        ArrayTools.printInts(numbers);
    }

    public static void bubbleSort(int[] numbers) {
        for (int i = 0; i < numbers.length - 1; i++) {
            for (int j = 0; j < numbers.length - 1 - i; j++) {
                if (numbers[j] > numbers[j + 1])
                    ArrayTools.swap(numbers, j, j + 1);
            }
        }
    }

选择排序 

    public static void main(String[] args) throws Exception {
        int[] numbers = ArrayTools.getRandomInts2(7, -9, 9);
        ArrayTools.printInts(numbers);
        selectSort(numbers);
        ArrayTools.printInts(numbers);
    }
    
    public static int[] selectSort(int[] numbers) {
        int length = numbers.length;
        for (int i = 0; i < length - 1; i ++) {
            for (int j = i + 1; j < length; j ++) {
                if (numbers[i] > numbers[j]) {
                    ArrayTools.swap(numbers, i, j);
                }
            }
        }
        return numbers;
    }

猜你喜欢

转载自blog.csdn.net/anyuzun/article/details/84573754
今日推荐