heapsort

Heapsort is nota stable sort algorithm. In order to learn this algorithm, you need to knowsome concepts first.

Actually, theheap is a binary tree, in this tree a parent node has two children nodes. Theparent is greater than or less than the two children. There are twokinds of heaps, the difference between them is the order of the elements. Ifthe root is the maximum element, it could be called big top heap, if theroot is the minimum element, it could be called small top heap.

The idea of thisalgorithm is build a heap base on the array which is needed to be ordered.Ensure each parent is greater than or less than its two children in the heap,such that after a traversing, the root element will be themaximum or minimum one in the whole heap, than swap the root with the lastleaf node. After that, you should adjust the elements of the heapexcept that last leaf node, and then repeat the processwhich is described above. The last heap is neededto be adjusted will only have one element, and then finished the recursion. Atthe end, you will get an ordered heap.

We assume thatthe original array is needed to sort by ascending order. The detail steps areas followed:

1. Build a binary tree base on the initialarray.

2. Adjust the heap to ensure that parentnode is greater than the two children.

3. Swap the root element with the lastnode.

4. Make the heap except that last node as anew heap, and then recursively execute the step 2 and 3.

5. The recursion will be finished if theinput heap has only one element.

6. At last, you will get a sorted order.

The complexity of heapsort is alwaysO(nlgn).

The following is the implement of heapsortby java.

private void maxHeapify(int[] array, int i,int heapSize){
    int largestIndex = i;
    int leftIndex = 2*i+1;
    int rightIndex = 2*i+2;
    if(leftIndex < heapSize &&array[leftIndex] > array[largestIndex]){
        largestIndex = leftIndex;
    }
    if(rightIndex < heapSize&& array[rightIndex] > array[largestIndex]){
        largestIndex = rightIndex;
    }
    if(largestIndex != i){
        int temp = array[i];
        array[i] = array[largestIndex];
        array[largestIndex] = temp;
        maxHeapify(array,largestIndex,heapSize);
    }
}

private void buildMaxHeap(int[] array){
    for(int i = array.length/2;i >= 0;i--){
        maxHeapify(array,i,array.length);
    }
}

public void heapSort(int array[]){
    buildMaxHeap(array);
    for(int i = array.length-1;i > 0;i--){
        int temp = array[0];
        array[0] = array[i];
        array[i] = temp;
        maxHeapify(array,0, i-1);
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值