冒泡排序和选择排序

2020-04-01  本文已影响0人  futureluck

    public static void main(String[] args) {
        // 冒泡排序的思想,重点是内循环的相邻比较,交换的相邻的数据。
        // 选择排序的思想,重点是比较所有的剩下的元素取出最大的,是只有一个位置的数据进行交换,交互的是外循环下标的数据。
        maoPao();
        System.out.println("***********************");
        xuanZe();
    }


    public static void maoPao() {
        int[] a = {2, 6, 4, 5, 1, 7, 3};
        for (int i = 0; i < a.length - 1; i++) {
            for (int j = 0; j < a.length - 1 - i; j++) {
                if (a[j] < a[j + 1]) {
                    int n = a[j];
                    a[j] = a[j + 1];
                    a[j + 1] = n;
                }
            }
        }

        System.out.println(Arrays.toString(a));
    }

    public static void xuanZe() {
        int[] a = {2, 6, 4, 5, 1, 7, 3};

        for (int i = 0; i < a.length; i++) {
            for (int j = i + 1; j < a.length; j++) {
                if (a[i] > a[j]) {
                    int n = a[j];
                    a[j] = a[i];
                    a[i] = n;
                }
            }
        }
        System.out.println(Arrays.toString(a));
    }
上一篇 下一篇

猜你喜欢

热点阅读