排序算法(java)

1、堆排序

public class StackSort {

    public static void main(String[] args) {
        int[] a = new int[]{4, 3, 5, 2, 7, 9};
        sort(a);
        for (int i = 0; i < a.length; i++) {
            System.out.println(a[i]);
        }
    }

    public static void sort(int[] a) {
        int N = a.length;
        for (int i = N >> 1; i >= 1; i--) {
            sink(a, N, i);
        }
        while (N > 1) {
            exch(a, 1, N--);
            sink(a, N, 1);
        }
    }

    public static void sink(int[] a, int N, int k) {
        while (k << 1 <= N) {
            int j = k << 1;
            if (j < N && less(a, j, j + 1)) j++;
            if (!less(a, k, j)) break;
            exch(a, k, j);
            k = j;
        }
    }

    public static void exch(int[] a, int i, int j) {
        int temp = a[i-1];
        a[i-1] = a[j-1];
        a[j-1] = temp;
    }

    public static boolean less(int[] a, int i, int j) {
        return a[i-1] - a[j-1] < 0;
    }
}

2、快速排序

public class QuickSort {

    public static void main(String[] args) {
        int[] a = new int[]{3,5,2,4,6,1,3,7};
        sort(a, 0, a.length-1);
        for (int i: a) {
            System.out.println(i);
        }
    }

    public static void sort(int[] a, int lo, int hi) {
        if (lo >= hi) return;
        int j = partition(a, lo, hi);
        sort(a, lo, j-1);
        sort(a, j+1, hi);
    }

    public static int partition(int[] a, int lo, int hi) {
        int i = lo, j = hi + 1;
        int v = a[lo];
        while (true) {
            while (a[++i] < v) if (i == hi) break;
            while (a[--j] > v) if (j == lo) break;;
            if (i >= j) break;
            exch(a, i, j);
        }
        exch(a, lo, j);
        return j;
    }

    public static void exch(int[] a, int i, int j) {
        int temp = a[i];
        a[i] = a[j];
        a[j] = temp;
    }
}

3、归并排序

public class MergeSort {

    public static void main(String[] args) {
        int[] a = new int[]{5,2,3,9,5};
        int[] temp = new int[5];
        sort(a, temp, 0, a.length-1);
        for (int i: a) {
            System.out.println(i);
        }
    }

    public static void sort(int[] a, int[] temp, int lo, int hi) {
        if (lo >= hi) return;
        int mid = lo + (hi - lo) / 2;
        sort(a, temp, lo, mid);
        sort(a, temp, mid+1, hi);
        merge(a, temp, lo, hi, mid);
    }

    public static void merge(int[] a, int[] temp, int lo, int hi, int mid) {
        int i = lo, j = mid+1;
        for (int k = lo; k <= hi; k++) {
            temp[k] = a[k];
        }
        for (int k = lo; k <= hi; k++) {
            if (i > mid) a[k] = temp[j++];
            else if (j > hi) a[k] = temp[i++];
            else if (temp[i] > temp[j]) a[k] = temp[j++];
            else a[k] = temp[i++];
        }
    }
}

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