Java: Heap sort Algorithm
Write a Java program to sort an array of given integers using the Heap sort algorithm.
In computer science heapsort (invented by J. W. J. Williams in 1964) is a comparison-based sorting algorithm. Heapsort can be thought of as an improved selection sort: like that algorithm, it divides its input into a sorted and an unsorted region, and it interactively shrinks the unsorted region by extracting the largest element and moving that to the sorted region. The improvement consists of the use of a heap data structure rather than a linear-time search to find the maximum. Although somewhat slower in practice on most machines than a well-implemented quicksort, it has the advantage of a more favorable worst-case O(n log n) runtime. Heapsort is an in-place algorithm, but not a stable sort.
A run of the heapsort algorithm sorting an array of randomly permuted values. In the first stage of the algorithm the array elements are reordered to satisfy the heap property. Before the actual sorting takes place, the heap tree structure is shown briefly for illustration.
Animation credits : RolandH
Pseudocode:
Sample Solution:
Java Code:
Sample Output:
Sorted array: -5 0 1 2 3 7 45
Flowchart:
For more Practice: Solve these Related Problems:
- Write a Java program to implement heap sort and build the heap in O(n) time from an unsorted array.
- Write a Java program to modify heap sort to sort an array of objects based on a specified attribute.
- Write a Java program to implement heap sort in descending order by adjusting the heap condition.
- Write a Java program to implement a min-heap sort variation that sorts the array in ascending order using a min-heap.
Java Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a Java program to sort an array of given integers using Merge sort Algorithm.
Next: Write a Java program to sort an array of given integers using Selection Sort Algorithm.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.