什麼是堆排序,堆排序(代碼詳解)

下面爲推排序的一些代碼,僅供參考:

public class HeapSort<T extends Comparable<T>>{
    //判斷heap堆中索引i處的元素是否小於索引j處的元素
    private static boolean less(Comparable[] heap,int i,int j){
        return heap[i].compareTo(heap[j]) < 0;
    }

    //交換heap堆中i索引和j索引處的值、
    private static void exch(Comparable[] heap,int i,int j){
        Comparable temp = heap[i];
        heap[i] = heap[j];
        heap[j] = temp;
    }

    //根據原數組source,構造出堆heap
    private static void createHeap(Comparable[] source,Comparable[] heap){
        //把source中的元素拷貝到heap中,heap中的元素就形成一個無序的堆
        System.arraycopy(source,0,heap,1,source.length);

        //對堆中的元素做喲下沉調整(從一半處開始),往索引1處掃描
        for(int i = (heap.length)/2; i > 0; i--){

            //有堆的性質可以知道,在一半進行下沉就可以了;
            sink(heap,i,heap.length-1);
        }
    }

    //對source數組中的數據從小到大排序
    public static void sort(Comparable[] source){
        //構建堆
        Comparable[] heap = new Comparable[source.length + 1];
        createHeap(source,heap);
        //定義一個變量,記錄未排序的元素中最大的索引
        int N = heap.length-1;
        //通過循環,交換1索引處的元素和排序的元素中國最大的索引處的元素
        while (N != 1){
            //交換元素
            exch(heap,1,N);
            //排序交換後最大元素所在的索引,讓它不要參與堆的下沉調整
            N--;
            //需要對索引1處的元素進行下沉調整
            sink(heap,1,N);
        }

        //把heap中的數據複製到原數組sourse中
        System.arraycopy(heap,1,source,0,source.length);
    }

    //在heap堆中,對target處的元素做下沉,範圍是0~orange
    private static void sink(Comparable[] heap,int target,int range){

        while (2*target <= range){
            //1.找出當前結點的較大的子結點
            int max;
            if(2*target+1 <= range){
                if(less(heap,2*target,2*target+1)){
                    max = 2*target+1;
                }else {
                    max = 2*target;
                }
            }else {
                max = 2*target;
            }

            //2.比較當前結點的值和較大子結點的值
            if(less(heap,max,target)){
                break;
            }else {
                //交換值
                exch(heap,max,target);
                //變換target
                target = max;
            }
        }
    }

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章