欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

冒泡/选择排序Demo

程序员文章站 2024-03-20 20:31:16
...

冒泡排序

    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;
    }