堆排序

public class HeapSort {
    public static void heapSort(int[] data, int n)
    {
        int tmp;
        int unsorted = n;
        makeHeap(data, n);
        while(unsorted > 0)
        {
            unsorted--;
            tmp = data[0];
            data[0] = data[unsorted];
            data[unsorted] = tmp;
            reheapifyDown(data, unsorted);
        }
    }
    private static void makeHeap(int[] data, int n)
    {
        int tmp;
        int parent;
        for(int i = 1; i < n; i ++)
        {
            while((!isRoot(i)) && data[i] > data[parent(i)])
            {
                parent = parent(i);
                tmp = data[i];
                data[i] = data[parent];
                data[parent] = tmp;
                i = parent;
            }
        }
    }
    private static boolean isRoot(int i)
    {
        return i == 0 ? true : false;
    }
    private static int parent(int i)
    {
        return (i - 1) / 2;
    }
    private static boolean isLeaf(int i, int unsort)
    {
        return (2 * i + 1) < unsort ? false:true;
    }
    private static void reheapifyDown(int[] data, int n)
    {
        int i = 0;
        int tmp;
        int maxIndex;
        boolean heapOkay = false;
        while((!isLeaf(i, n)) && (!heapOkay) )
        {
            maxIndex = maxIndexOfChild(data, n, i);
            if(data[maxIndex] > data[i])
            {
                tmp = data[i];
                data[i] = data[maxIndex];
                data[maxIndex] = tmp;
                i = maxIndex;
            }
            else
                heapOkay = true;
        }
    }
    private static int maxIndexOfChild(int[] data, int unsort, int i)
    {
        if(isLeaf(i, unsort))
            return i;
        else if(2*i + 2 == unsort)
        {
            return 2*i + 1;
        }
        else
        {
            return data[2*i+1] > data[2*i + 2] ? (2*i + 1) : (2*i + 2);
        }
    }
    public static void main(String[] args)
    {
        int[] data = new int[]{1, 3, 2, 9, 3, 9, 8};
        HeapSort.heapSort(data, data.length);
        for(int i = 0; i < data.length; i ++)
        {
            System.out.println(data[i]);
        }
    }
}


你可能感兴趣的:(堆排序)