java五种常见排序算法

    public static void main(String[] args) {
        int[] arr = {3, 5, 7, 1, 6, 2, 4};
        bubbleSort(arr);
        selectSort(arr);
        insertSort(arr);
        shellSort(arr);
        quickSort(arr, 0, arr.length - 1);
    }

    //冒泡
    public static void bubbleSort(int[] arr) {
        for (int i = 0; i < arr.length - 1; i++) {
            boolean flag = false;
            for (int j = 0; j < arr.length - 1 - i; j++) {
                if (arr[j] > arr[j + 1]) {
                    flag = true;
                    int temp = arr[j + 1];
                    arr[j + 1] = arr[j];
                    arr[j] = temp;
                }
            }
            if (!flag) {
                return;
            }
        }

    }

    //选择
    public static void selectSort(int[] arr) {
        for (int i = 0; i < arr.length - 1; i++) {
            int min = i;
            for (int j = i + 1; j < arr.length; j++) {
                if (arr[min] > arr[j]) {
                    min = j;
                }
            }
            if (min != i) {
                int temp = arr[min];
                arr[min] = arr[i];
                arr[i] = temp;
            }
        }
    }

    //插入
    public static void insertSort(int[] arr) {
        for (int i = 1; i < arr.length; i++) {
            int insert = i - 1;
            int temp = arr[i];
            while (insert >= 0 && temp < arr[insert]) {
                arr[insert + 1] = arr[insert];
                insert--;
            }
            arr[insert + 1] = temp;
        }
    }

    //希尔(插入的优化)
    public static void shellSort(int[] arr) {
        for (int gap = arr.length / 2; gap > 0; gap /= 2) {
            for (int i = gap; i < arr.length; i++) {
                int insert = i;
                int temp = arr[i];
                while (insert - gap >= 0 && temp < arr[insert - gap]) {
                    arr[insert] = arr[insert - gap];
                    insert -= gap;
                }
                arr[insert] = temp;
            }
        }
    }

    //快速
    public static void quickSort(int[] arr, int left, int right) {
        if (left >= right) {
            return;
        }
        int base = arr[left];
        int i = left;
        int j = right;
        while (i != j) {
            while (i < j && arr[j] >= base) {
                j--;
            }
            while (i < j && arr[i] <= base) {
                i++;
            }
            int temp = arr[j];
            arr[j] = arr[i];
            arr[i] = temp;
        }
        arr[left] = arr[i];
        arr[i] = base;

        quickSort(arr, left, i - 1);
        quickSort(arr, j + 1, right);
    }

 

你可能感兴趣的:(算法)