Heap sorting and its application in java

Heap sort

1. The concept of heap sort:

     (1) Heap sorting is a sorting algorithm designed by using the data structure of the heap, and it is a tree-shaped selection sorting method;

     (2) Heap sorting is an unstable sorting, which means that for numbers of the same size, their relative positions will change after sorting;

     (3) The heap is a complete binary tree with the following properties: The value of each node is greater than or equal to the value of its left and right child nodes, which becomes the big top heap; the value of each node is less than or equal to the value of its left and right nodes, and becomes the small Top pile

     (4) Heap is often used to implement priority queues;

     (5) Heap sorting is the best and the worst, and the average time complexity is O(nlogn)


2. Schematic diagram of large top pile and small top pile:

       

Numbering the middle-heap nodes of the large-top heap and mapping to the array meets the following characteristics:

         

The formula description is:

大顶堆:arr[i] >= arr[2i+1] && arr[i] >= arr[2i+2]  

小顶堆:arr[i] <= arr[2i+1] && arr[i] <= arr[2i+2] 


3. The basic idea of ​​heap sort:

    The basic idea of ​​sorting is to construct the sequence to be sorted into a large top pile. At this time, the maximum value of the entire sequence is the root node of the top of the pile. Exchange it with the last element, and the end is the maximum value at this time. Then reconstruct the remaining n-1 elements into a pile, so that the next smallest value of n elements will be obtained. Such repeated execution will result in an ordered sequence. Generally, a large top stack is used in ascending order, and a small top stack is used in descending order.

 Step 1 Construct the initial heap.

 

Step 2: Start from the last non-leaf node, adjust from left to right, and from bottom to top.

Step 3: Find the second non-leaf node 4, since 9 elements in [4,9,8] are the largest, 4 and 9 are exchanged.

Step 4 The exchange resulted in the disorder of the sub-root [4,5,6], continue to adjust, [4,5,6] 6 is the largest, exchange 4 and 6.

At this point, we have completed the construction of a disordered sequence into a large top pile. We need to do further work on the basis of the large top heap, in order to achieve the purpose of arranging the array in descending order.

Step 1: Exchange the top element 9 and the last element 4 of the heap

Step 2: Re-adjust the structure and adjust the remaining elements to meet the requirements of the large top pile

Step 3: Exchange the top element and the end element again

Subsequent repeated adjustments and exchanges will eventually make the entire sequence orderly

4. Code implementation:

               

package sortdemo;

import java.util.Arrays;

/**
 * 堆排序demo
 */
public class HeapSort {
    public static void main(String []args){
        int []arr = {9,8,7,6,5,4,3,2,1};
        sort(arr);
        System.out.println(Arrays.toString(arr));
    }
    public static void sort(int []arr){
        //1.构建大顶堆
        for(int i=arr.length/2-1;i>=0;i--){
            //从第一个非叶子结点从下至上,从右至左调整结构
            adjustHeap(arr,i,arr.length);
        }
        //2.调整堆结构+交换堆顶元素与末尾元素
        for(int j=arr.length-1;j>0;j--){
            swap(arr,0,j);//将堆顶元素与末尾元素进行交换
            adjustHeap(arr,0,j);//重新对堆进行调整
        }

    }

    /**
     * 调整大顶堆(仅是调整过程,建立在大顶堆已构建的基础上)
     * @param arr
     * @param i
     * @param length
     */
    public static void adjustHeap(int []arr,int i,int length){
        int temp = arr[i];//先取出当前元素i
        for(int k=i*2+1;k<length;k=k*2+1){//从i结点的左子结点开始,也就是2i+1处开始
            if(k+1<length && arr[k]<arr[k+1]){//如果左子结点小于右子结点,k指向右子结点
                k++;
            }
            if(arr[k] >temp){//如果子节点大于父节点,将子节点值赋给父节点(不用进行交换)
                arr[i] = arr[k];
                i = k;
            }else{
                break;
            }
        }
        arr[i] = temp;//将temp值放到最终的位置
    }

    /**
     * 交换元素
     * @param arr
     * @param a
     * @param b
     */
    public static void swap(int []arr,int a ,int b){
        int temp=arr[a];
        arr[a] = arr[b];
        arr[b] = temp;
    }
}

5. Summary:

            Heap sorting is a kind of selective sorting, and the whole is mainly composed of three parts: initial heap (ascending order to construct large top heap, descending order to construct small top heap) + swapping top elements and last elements + reconstruction heap. The time complexity of constructing the initial heap is O(n). In the process of swapping and rebuilding the heap, it needs to be swapped n-1 times. In the process of rebuilding the heap, according to the nature of the complete binary tree, [log2(n-1) ,log2(n-2)...1] gradually decreases, approximately nlogn. Therefore, the time complexity of heap sorting is generally considered to be O(nlogn) level.

 

Guess you like

Origin blog.csdn.net/u014753478/article/details/114253290