Java Program to Implement Heap Sort Using Library Functions

Problem Description

Given an array of integers, sort the array using heapsort algorithm, as built into the library.

Problem Solution

The idea is to create a priority queue of the array elements. A priority queue is a min-heap. Extract the elements from the priority queue one by one and store them in the array. The array obtained will be sorted.

Program/Source Code

Here is the source code of the Java Program to Implement Heap Sort Using Library Functions. The program is successfully compiled and tested using IDE IntelliJ Idea in Windows 7. The program output is also shown below.

//Java Program to Implement Heap Sort Using Library Functions
 
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.PriorityQueue;
 
public class HeapSortLib {
    // Function to implement heapsort using priority queue
    static void libraryHeapSort(int[] array){
        PriorityQueue<Integer> priorityQueue = new PriorityQueue<>();
        int i;
        for(i=0; i<array.length; i++){
            priorityQueue.add(array[i]);
        }
        i=0;
        while(!priorityQueue.isEmpty()){
            array[i++] = priorityQueue.poll();
        }
    }
    // Function to read user input
    public static void main(String[] args) {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int size;
        System.out.println("Enter the size of the array");
        try {
            size = Integer.parseInt(br.readLine());
        } catch (Exception e) {
            System.out.println("Invalid Input");
            return;
        }
        int[] array = new int[size];
        System.out.println("Enter array elements");
        int i;
        for (i = 0; i < array.length; i++) {
            try {
                array[i] = Integer.parseInt(br.readLine());
            } catch (Exception e) {
                System.out.println("An error Occurred");
            }
        }
        System.out.println("The initial array is");
        System.out.println(Arrays.toString(array));
        libraryHeapSort(array);
        System.out.println("The sorted array is");
        System.out.println(Arrays.toString(array));
    }
}

Program Explanation

1. The function libraryHeapSort(), a priority queue is created.
2. The loop for(i=0; i<array.length; i++), adds the enemy elements to the priority queue.
3. The loop while(!priorityQueue.isEmpty()) extracts the elements from priority queue one by one and then adds them to the queue.

Time Complexity: O(n*log(n)) where n is the number of elements in the array.

Runtime Test Cases

Case 1 (Simple Test Case):
 
Enter the size of the array
5
Enter array elements
9
8
7
6
5
The initial array is
[9, 8, 7, 6, 5]
The sorted array is
[5, 6, 7, 8, 9]
 
Case 2 (Simple Test Case - another example):
 
Enter the size of the array
8
Enter array elements
8
7
6
9
9
6
7
8
The initial array is
[8, 7, 6, 9, 9, 6, 7, 8]
The sorted array is
[6, 6, 7, 7, 8, 8, 9, 9]

Related posts:

Tạo ứng dụng Java RESTful Client không sử dụng 3rd party libraries
Java Program to Implement the Alexander Bogomolny’s UnOrdered Permutation Algorithm for Elements Fro...
Java Program to Represent Linear Equations in Matrix Form
Sử dụng JDBC API thực thi câu lệnh truy vấn dữ liệu
Java Program to Test Using DFS Whether a Directed Graph is Strongly Connected or Not
Initialize a HashMap in Java
OAuth2.0 and Dynamic Client Registration
Introduction to the Java ArrayDeque
Hướng dẫn Java Design Pattern – Abstract Factory
Spring Cloud – Securing Services
Derived Query Methods in Spring Data JPA Repositories
Guide to the Volatile Keyword in Java
Tìm hiểu về xác thực và phân quyền trong ứng dụng
Lớp Arrarys trong Java (Arrays Utility Class)
Java Program to Implement Floyd Cycle Algorithm
Java Program to Search Number Using Divide and Conquer with the Aid of Fibonacci Numbers
Java Program to Check Whether Topological Sorting can be Performed in a Graph
A Guide to BitSet in Java
Java – Write to File
How to Get a Name of a Method Being Executed?
Java Program to Find Hamiltonian Cycle in an UnWeighted Graph
Java Program to Perform Searching Using Self-Organizing Lists
Apache Commons Collections BidiMap
Java Program to Find the Median of two Sorted Arrays using Binary Search Approach
Guide to java.util.Formatter
Java Program to Implement K Way Merge Algorithm
Java Program to subtract two large numbers using Linked Lists
Uploading MultipartFile with Spring RestTemplate
Java Switch Statement
Java Program to Implement a Binary Search Algorithm for a Specific Search Sequence
Hướng dẫn sử dụng Printing Service trong Java
Java Program to Check whether Undirected Graph is Connected using BFS