Java Program to Implement Heap Sort on an Array of n Elements – Sanfoundry

This is the Java Program to Implement Heap Sort on an Array of n Elements.

Problem Description

Given an array of integers, sort the array using heap sort algorithm.

Problem Solution

The idea is to create a max heap of the array elements. Then, obtain the maximum element from the heap, interchange it with the last element and finally heapify the remaining (n-1) elements. Repeat this procedure until zero elements are left.

Program/Source Code

Here is the source code of the Java Program to Implement Heap Sort on an Array of n Elements. The program is successfully compiled and tested using IDE IntelliJ Idea in Windows 7. The program output is also shown below.

  1.  
  2. //Java Program to Implement Heap Sort on an Array of n Elements
  3. import java.io.BufferedReader;
  4. import java.io.InputStreamReader;
  5. import java.util.Arrays;
  6.  
  7. public class HeapSort {
  8.     //Function to sort the array using heapsort
  9.     static void heapSort(int[] array){
  10.              buildHeap(array);
  11.              int i,temp = array.length-1;
  12.              for(i = array.length-1; i>=1; i--){
  13.                  int x = array[0];
  14.                  array[0] = array[temp];
  15.                  array[temp] = x;
  16.                  temp--;
  17.                  heapifyDownwards(array,0,temp);
  18.              }
  19.     }
  20.     // Function to heapify the array
  21.     static void heapifyDownwards(int[] array,int i,int n){
  22.         if(i>n)
  23.         {
  24.             return;
  25.         }
  26.         int left,right,index = i;
  27.         left = 2*i;
  28.         right= 2*i+1;
  29.         boolean change = false;
  30.         if(left<=n && array[i]<array[left]){
  31.             index = left;
  32.             change = true;
  33.         }
  34.         if(right<=n && array[right]>array[index]){
  35.             index = right;
  36.             change = true;
  37.         }
  38.         if(!change)
  39.         {
  40.             return;
  41.         }
  42.         int temp = array[index];
  43.         array[index] = array[i];
  44.         array[i] = temp;
  45.         heapifyDownwards(array,index,n);
  46.     }
  47.     // Function to build a max-heap
  48.     static void buildHeap(int[] array){
  49.         int i = array.length/2-1;
  50.         for(;i>=0;i--){
  51.             heapifyDownwards(array,i,array.length-1);
  52.         }
  53.     }
  54.     // Function to read input and display the output
  55.     public static void main(String[] args) {
  56.         BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  57.         int size;
  58.         System.out.println("Enter the size of the array");
  59.         try {
  60.             size = Integer.parseInt(br.readLine());
  61.         } catch (Exception e) {
  62.             System.out.println("Invalid Input");
  63.             return;
  64.         }
  65.         int[] array = new int[size];
  66.         System.out.println("Enter array elements");
  67.         int i;
  68.         for (i = 0; i < array.length; i++) {
  69.             try {
  70.                 array[i] = Integer.parseInt(br.readLine());
  71.             } catch (Exception e) {
  72.                 System.out.println("An error Occurred");
  73.             }
  74.         }
  75.         System.out.println("The initial array is");
  76.         System.out.println(Arrays.toString(array));
  77.         heapSort(array);
  78.         System.out.println("The sorted array is");
  79.         System.out.println(Arrays.toString(array));
  80.     }
  81. }

Program Explanation

1. The function buildHeap() is used to build a max-heap from the array elements. It starts from the internal nodes of the heaps and heapifies them downwards.
2. In function heapifyDownwards(), the element at index i, is compared with its children. If any child is greater than the parent, the nodes are swapped and the function is called recursively on the children.
3. In function heapSort(), firstly the buildHeap function is called.
4. The loop for(i = array.length-1; i>=1; i–), iterates through the heap swaps the first element with the last and heapifies the first element.

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]

Sanfoundry Global Education & Learning Series – Java Programs.

Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Leave a Comment

Your email address will not be published. Required fields are marked *