冒泡排序

public class BubbleSort {

    public static void main(String[] args) {
        int[] ints = {7, 6, 5, 4, 3, 2, 1};
        bubble(ints);
        print(ints);
    }

    public static void bubble(int[] ints) {
        int count = 0;
        int count2 = 0;
        for (int i = ints.length - 1; i > 0; i--) {
            for (int j = 0; j < i; j++) {
                count++;
                if (ints[j] > ints[j + 1]) {
                    int temp;
                    temp = ints[j + 1];
                    ints[j + 1] = ints[j];
                    ints[j] = temp;
                    count2++;
                }
            }
        }
        System.out.println("比较次数: " + count);
        System.out.println("交换次数: " + count2);
    }

    public static void print(int[] ints) {
        System.out.println("冒泡排序结果:");
        for (int i = 0; i < ints.length; i++) {
            System.out.print(ints[i] + " ");
        }
    }
}

比较次数: 21
交换次数: 21
冒泡排序结果:
1 2 3 4 5 6 7

选择排序


public class SelectSort {

    public static void main(String[] args) {
        int[] ints = {7, 6, 5, 4, 3, 2, 1};
        select(ints);
        print(ints);
    }

    public static void select(int[] ints) {
        int count = 0;
        int count2 = 0;
        for (int i = 0; i < ints.length - 1; i++) {
            //默认指定最左边的元素是最小的元素
            int min = i;
            for (int j = i + 1; j < ints.length; j++) {
                count++;
                if (ints[j] < ints[min]) {
                    count2++;
                    min = j;
                }
            }
            //min不等于i说明最小元素不是之前指定的最左边元素
            if (min != i) {
                //执行交换
                int temp;
                temp = ints[min];
                ints[min] = ints[i];
                ints[i] = temp;
            }
        }
        System.out.println("比较次数: " + count);
        System.out.println("交换次数: " + count2);
    }

    public static void print(int[] ints) {
        System.out.println("选择排序结果:");
        for (int i = 0; i < ints.length; i++) {
            System.out.print(ints[i] + " ");
        }
    }
}

比较次数: 21
交换次数: 12
选择排序结果:
1 2 3 4 5 6 7

分类: 算法专栏

Deng Jia

Keep Moving.

0 条评论

发表评论

电子邮件地址不会被公开。