堆排序

50 阅读1分钟
package sort;

public class HeapSort {

    public static void main(String[] args) {
        int[] a = {4, 6, 3, 7, 1, 9, 2, 8, 5};
        sort(a);
        for (int i : a) {
            System.out.print(i+" ");
        }
    }

    public static void sort(int[] a) {
        for (int i = a.length - 1; i > 0; i--) {
            heap(a, i);
            swap(a, 0, i);
        }

    }

    public static void heap(int[] a, int end) {
        int lastParent = (end - 1) / 2;
        for (int i = lastParent; i >= 0; i--) {
            int left = i * 2 + 1;
            int right = i * 2 + 2;
            int max = i;
            if (right <= end && a[right] > a[max]) max = right;
            if (a[left] > a[max]) max = left;
            if (i != max) {
                swap(a,i,max);
            }
        }
    }

    public static void swap(int[] a, int x, int y) {
        int tmp = a[x];
        a[x] = a[y];
        a[y] = tmp;
    }
}