Basic heap sort (Java sample code)

Table of contents

 

Basic heap sort

1. Concept and introduction

2. Applicable instructions

3. Process Diagram

4. Java example code

src/runoob/heap/Heapify.java file code:


 

Basic heap sort

1. Concept and introduction

Heapsort (Heapsort) refers to a sorting algorithm designed using the data structure of the heap.

A heap is a structure that approximates a complete binary tree, and at the same time satisfies the nature of accumulation: that is, the key value or index of a child node is always smaller (or larger) than its parent node.

2. Applicable instructions

Our previous process of constructing a heap is to call the insert method and use shift up to insert data into the heap one by one. The time complexity of this algorithm is O(nlogn). The process of constructing a heap sort introduced in this section is called Heapify , the time complexity of the algorithm is O(n) .

3. Process Diagram

An important property of a complete binary tree is that the index of the first non-leaf node is the index value obtained by taking an integer from n/2 , where n is the number of elements (provided that the array index starts from 1).

 

8533aeaabb8bcf09d2f2cd103cd9ff0e.png

The position of index 5 is the first non-leaf node, and we start from it one by one and carry out the shift down operation on each element as the root node to satisfy the nature of the maximum heap.

After the shift down operation is performed at index 5, 22 and 62 exchange positions.

 

5e791e13029e315ffdf601d7dac7837f.png

Perform shift down operation on the index 4 element

 

78f5380da0c82c652b1bc821a8b0236e.png

Perform shift down operation on the index 3 element

 

d88f077f5f376a8aeaf89f450e7d57ff.png

Perform shift down operation on the index 2 element

 

61f8df73255048aae76de8b24454c38e.png

Finally, perform a shift down operation on the root node, and the entire heap sorting process is completed.

 

dc779b8bcc78fd27af078d7b2f4d7819.png

4. Java example code

Source package download: Download https://www.runoob.com/wp-content/uploads/2020/09/runoob-algorithm-Heapify.zip

src/runoob/heap/Heapify.java file code:

package runoob.heap;

import runoob.sort.SortTestHelper;

/**
 * Use heapify for heap sorting
 */
public class Heapify<T extends Comparable> {     protected T[] data;     protected int count;     protected int capacity;     // constructor , Create a maximum heap through a given array     // The process of constructing a heap, the time complexity is O(n)     public Heapify(T arr[]){         int n = arr.length;         data = (T[])new Comparable[n+1];         capacity = n;         for( int i = 0 ; i < n ; i ++ )             data[i+1] = arr[i];         count = n;         // from the first not leaf The element of the node starts         for( int i = count/2 ; i >= 1 ; i -- )             shiftDown(i);




















    }
    // Return the number of elements in the heap
    public int size(){         return count;     }     // Return a Boolean value indicating whether the heap is empty     public boolean isEmpty(){         return count == 0;     }     // Like the largest Insert a new element into the heap item     public void insert(T item){         assert count + 1 <= capacity;         data[count+1] = item;         count ++;         shiftUp(count);     }     // take out from the max heap The top element of the heap, that is, the maximum data stored in the heap     public T extractMax(){         assert count > 0;         T ret = data[1];         swap( 1 , count );         count --;         shiftDown(1);         return ret;





















    }
    // Get the top element in the maximum heap
    public T getMax(){         assert( count > 0 );         return data[1];     }     // Exchange the two elements with indexes i and j in the heap     private void swap(int i, int j){         T t = data[i];         data[i] = data[j];         data[j] = t;     }     //************** ****     //* Max Heap Core Helper Function     //********************     private void shiftUp(int k){         while( k > 1 && data[ k/2].compareTo(data[k]) < 0 ){             swap(k, k/2);             k /= 2;         }     }     private void shiftDown(int k){         while( 2*k <= count ){


























            int j = 2*k; // In this cycle, data[k] and data[j] exchange positions
            if( j+1 <= count && data[j+1].compareTo(data[j]) > 0 )
                j ++;
            // data[j] is the maximum value of data[2*k] and data[2*k+1]

            if( data[k].compareTo(data[j]) >= 0 ) break;
            swap(k, j);
            k = j;
        }
    }

    // test heapify
    public static void main(String[] args) {         int N = 100;         Integer[] arr = SortTestHelper.generateRandomArray(N, 0, 100000) ;         Heapify<Integer> heapify = new Heapify<Integer>(arr);         // Gradually extract the data in heapify using extractMax         // The order of extracting should be from large to small





        for( int i = 0 ; i < N ; i ++ ){             arr[i] = heapify.extractMax();             System.out.print(arr[i] + " ");         }         // Make sure the arr array is from         For( int i = 1 ; i < N ; i ++ )             assert arr[i-1] >= arr[i] ;     } }








 

Guess you like

Origin blog.csdn.net/2301_78835635/article/details/132163995