Data structure and algorithm (tree structure, practical application, heap sorting)

Basic introduction to heap sorting

(1) Heap sort is a sort algorithm designed by using the data structure heap. Heap sort is a selective sort. Its worst, best, average time complexity is O(nlogn), and it is also an unstable sort

(2) 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 is called large top heap,

Note: there is no size relationship between the left child's value and the right child's value of the node

(3) The value of each node is less than or equal to the value of its left and right child nodes, which is called small top heap

(4) Example of large top reactor

The nodes in the heap are numbered by layer and mapped to the array, as described below

  Characteristics of large top pile: arr [i] > = arr [2 * I + j + 1] & & arr [i] > = arr [2 * I + 2]

i corresponds to the number of nodes, and i is numbered from 0  

(5) Small top pile example

  Small top pile: arr [i] < = arr [2 * I + 1] & & arr [i] < arr [2 * I + 2]  

i corresponds to the number of nodes, and i is numbered from 0

(6) Generally, large top pile is used in ascending order and small top pile is used in descending order

Basic idea of heap sorting

(1) The sequences to be sorted form a large top heap

(2) At this point, the maximum value of the whole sequence introduces the following node at the top of the heap

(3) Swap it with the element at the end, where the end is the maximum

(4) Then, the remaining n-1 elements are reconstructed into a heap, which will get the sub small values of N element elements. After repeated execution, an ordered sequence can be obtained

You can see that in the process of building the large top heap, the elements are reduced one by one, and finally an ordered sequence can be obtained

Illustration of heap sorting steps:

Requirements: give you an array {4,, 6,8,5,9}. It is required to use heap sorting to sort the array in ascending order

Step 2: exchange the top element with the last element to maximize the last element, then continue to adjust the heap, and then exchange the top element with the last element to obtain the second largest element. Repeat the exchange, reconstruction and exchange

(1) Swap top element 9 and end element 4

(2) Restructure so that it continues to meet the heap definition

(3) Then exchange the top element 8 with the end element 5 to obtain the second largest element 8

(4) In the subsequent process, continue to adjust and exchange, so as to make the whole sequence orderly

Then briefly summarize the basic idea of heap elements:

(1) The unordered sequence is constructed into a heap, and the large top heap or small top heap is selected according to the ascending and descending requirements;

(2) Exchange the top element with the end element, and "sink" the largest element to the end of the array;

(3) Readjust the structure to meet the heap definition, and then continue to exchange the heap top element with the current tail element; Repeat the adjustment + exchange step until the whole sequence is in order

Code implementation:

package tree;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;

/**
 * Heap sort 8 million data for about 3s, very fast
 */
public class HeapSort {

    public static void main(String[] args) {
        //Requires the array to be sorted in ascending order
        //int arr[] = {4, 6, 8, 5, 9};
        //heapSort(arr);
        int []arr =new int[8000000];
        for (int i=0; i<8000000; i++){
            arr[i]=(int)(Math.random()*80000);//Generate a [0800000] number
        }
        Date date1= new Date();
        SimpleDateFormat simpleDateFormat= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date1Str =simpleDateFormat.format(date1);
        System.out.println("Time before sorting="+date1Str);
        //Test heap sorting
        heapSort(arr);

        Date date2= new Date();
        String date2Str =simpleDateFormat.format(date2);
        System.out.println("Time after sorting="+date2Str);
    }
    //Write a heap sorting method
    public static void heapSort(int arr[]){
        int temp = 0;
        System.out.println("Heap sort!");

      /*  //Step by step
        adjustHeap(arr,1,arr.length);
        System.out.println("First "+ Arrays.toString(arr)); //4.9.8.5.6

        adjustHeap(arr,0,arr.length);
        System.out.println("The second "+ arrays. ToString (ARR))// 9.6.8.5.4
       */
        //Complete final code
        //The unordered sequence is constructed into a heap, and the large top heap or small top heap is selected according to the ascending and descending requirements
        for (int i = arr.length / 2 -1; i >=0; i--){
            adjustHeap(arr,i,arr.length);
        }
        /*
         * 2.The top element of the price heap is exchanged with the end element to "sink" the largest element to the end of the array;
         * 3.Readjust the structure to meet the heap definition, then continue to exchange the top and end elements of the heap, and repeat the adjustment and exchange steps until the whole sequence is in order
         */
        for (int j = arr.length-1; j > 0; j--){
            //exchange
            temp = arr[j];
            arr[j] = arr[0];
            arr[0] = temp;
            adjustHeap(arr,0,j);
        }
        //System.out.println("array =" + arrays. ToString (ARR))// 4.5.6.8.9
    }

    //Adjust an array (binary tree) to a large top heap
    /**
     *Function: adjust the tree of non leaf nodes corresponding to i into large top heap
     * For example, int arr [] = {4,6,8,5,9} = > I = 1 = > adjustheap = > get {4,9,8,5,6}
     * If we call adjustHeap again, the passed I = o = > gets {4,9,8,5,6} = > {9,6,8,5,4}
     * @param arr Array to be adjusted
     * @param i Represents the index of a non leaf node in the array
     * @param lenght Indicates how many elements continue to be adjusted, and the lenght is gradually decreasing
     */
    public static void adjustHeap(int arr[],int i, int lenght){
        int temp = arr[i];//First take out the value of the current element and save the temporary variable
        //Start adjustment
        //explain
        //1.k = i * 2 + 1 k is the left child of node i
        for (int k = i * 2 + 1; k < lenght; k = k *2 + 1){
            if (k+1 < lenght && arr[k] < arr[k+1]){ //Indicates that the value of the left node is less than that of the right node
                k++; //k points to the right node
            }
            if (arr[k] > temp){ //If the child node is larger than the parent node
                arr[i] = arr[k]; //Assign a larger value to the current node
                i = k; //i points to k and continues the cyclic comparison
            }else {
                break;//
            }
        }
        //When the for loop ends, we have placed the maximum value of the tree with i as the parent node at the top (local)
        arr[i] = temp; //Put the temp value in the adjusted position
    }
}

Tags: Algorithm data structure

Posted on Tue, 30 Nov 2021 08:00:09 -0500 by rich___