Seven java heap sort sort --4_

HEAPSORT:

Selection Sort and similar elements are divided into rows to be ordered and disordered interval interval, to find the maximum number of sections from the disorder, and disorder section it
is exchanged the last number, the new order as a first section the number
Although the idea of sorting and selecting the same, but the method to find the maximum interval disorder is different. Heapsort certainly used the heap:
Each time the number of intervals to be re-disordered big top of the heap again, then the maximum value is top of the heap of elements, the top of the heap with the last big top stack elements after removing
exchange element . But the biggest element is no longer involved in big top HEAPSORT next
Seven java heap sort sort --4_
Seven java heap sort sort --4_

Code

 public static void heapSort(int[] array) {
        createHeap(array, array.length);
        for (int i = 0; i < array.length - 1; i++) {
            // 无序 [0, array.length - i)
            swap(array, 0, array.length - i - 1);
            // 无序 [0, array.length - i - 1)
            // 无序区间的长度: array.length - i - 1
            heapify(array, array.length - i - 1, 0);
        }
    }

    private static void createHeap(int[] array, int length) {
        for (int i = (length - 2) / 2; i >= 0; i--) {
            heapify(array, length, i);
        }
    }

private static void heapfify(int[] array,int size,int index){
            while(true){//结束条件使调整到没有孩子结点就跳出
            int left=2*index+1;//调整位置的左孩子
            if(left>=size){//表示没有孩子,不用再调整
                return ;
            }
            int max=left;
            int right=left+1;//右孩子
            if(right<size&&array[right]>array[left]){
                    max=right;//比较两个孩子的大小,选出最大的,再和双亲结点比较
            }
            if(array[max]<=array[index]){
                break;
            }
            if(array[max]>array[index]){
                swap(array,max,index);//如果孩子大,就交换
                index=max;//并再对交换后的分支进行调整
            }
        }
    }
private static void swap(int[] array, int i, int j) {
        int t = array[i];
        array[i] = array[j];
        array[j] = t;
    }

Guess you like

Origin blog.51cto.com/14234228/2434822