两种排序算法

2018-11-16  本文已影响0人  我就是个帝帝

冒泡排序代码


public class BubbelSort {
    public static void main(String[] args) {
        final int N = 5;
        int[] numbers = new int[N];
        Random random = new Random();
        for(int i = 0; i < N; i++){
            numbers[i] = random.nextInt(100);
        }

        System.out.print("排序前:");
        //遍历一维数组
        for (int n:numbers
             ) {
            System.out.print(n+ "  ");
        }
        //外层循环控制排序趟数
        int temp;
        for(int i = 0; i < N-1; i++){
            //内层循环控制每趟的排序次数
            for (int j = i+1; j < N; j++){
                if (numbers[i] < numbers[j]){
             temp = numbers[i];
             numbers[i] = numbers[j];
             numbers[j] = temp;
                }
            }
        }
        System.out.print("\n排序后:");

        for (int n:numbers
        ) {
            System.out.print(n+ "  ");
        }
    }
}

选择排序法


public class selectSort {
    public static void main(String[] args) {
        final int N = 5;
        int[] number = new int[N];
        Random random = new Random();
        for (int i = 0; i < N; i++){
            number[i] = random.nextInt(100);
        }
        System.out.print("排序前:");
        //遍历一维数组
        for (int n:number
        ) {
            System.out.print(n+ "  ");
        }
        int min;
        int temp;
        for (int i = 0; i < N-1; i++){
            min = i;
            for (int j = i + 1; j< N; j++){
                if (number[j] < number[min]){
                    min = j;
                }
            }
            if (i != min){
                temp = number[i];
                number[i] = number[min];
                number[min] = temp;
            }
        }
        System.out.print("\n排序后的结果为:");
        for (int n:number
             ) {
            System.out.print(n+" ");
        }
    }
}
上一篇 下一篇

猜你喜欢

热点阅读