十大经典排序算法 Java 实现

434 阅读1分钟

参考:zhuanlan.zhihu.com/p/57088609

选择排序 SelectSort

// 2组for循环 [0, n-1) [1, n)
// int min = i 往后找小的 min 和 i 交换

public class SelectSort {
    public static int[] selectSort(int[] a) {
        if (a == null) {
            return a;
        }
        int n = a.length;
        for (int i = 0; i < n - 1; i++) {
            int min = i;
            for (j = i + 1, j < n; j++) {
                if (a[j] < a[min]) {
                    min = j;
                }
            }
            swap(a, min, i);
        }
        return a;
    }
}

插入排序 InsertSort

// 2层for循环 [1,n) [0,i-1)
// int temp = a[i],如果元素 i-1 > i,往后移动
// i 位置插入 temp
public class InsertSort {
    public static int[] insertSort(int[] a) {
        if (a == null || a.length < 2) {
            return a;
        }
        int n = a.length;
        for (int i = 1; i < n; i++) {
            int temp = a[i];
            int j = i - 1;
            for (; j >= 0 && temp < a[j]; j--) {
                a[j + 1] = a[j];
            }
            a[j + 1] = temp;
        }
        return a;
    }
}

冒泡排序 BubbleSort

// 2层for循环 [0,n) [0,n-i-1)
// 后面比前面小则交换
public class BubbleSort {
    public static int[] BubbleSort(int[] a) {
        if (a == null || a.length < 2) {
            return a;
        }
        int n = a.length;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n - 1 - i; j++) {
                if (a[j + 1] < a[j]) {
                    swap(a, j + 1, j);
                }
            }
        }
        return a;
    }
}