Reading this tutorial will help you to learn how to implement heap sort using the Java programming language. Before going straight to the program, let’s understand what a heap sort is. As the concept of heap sort becomes clear, Programming and implementing it becomes a breeze.
What is heap sort?
Heap sort is a simple sorting technique that follows the binary data structure. It’s a version of the sorting technique. Out of given an array of numbers, you need to find the smallest one and place it as the initial element of the array.
It is a recursive algorithm where you follow the same step for each member of the array.
What is a binary heap?
A binary heap is a data structure where all the elements get allotted with a number. Each level places elements as left as possible. Property of the binary heap complies with rules of arrays.
In addition, there are three variants of the binary heap: min and max. As the name suggests, the key element in the min heap has the smallest value in comparison with other elements in the heap.
The same rule recursively applies to all the nodes of a binary tree.
Why binary heap array-based representation?
A binary heap follows the characteristics of a binary tree. You can express it in the form of an array. Array-based representation of data is space-efficient and has the least running time. Supposing that you store the least element at node i, parent elements are placed at 2*i+1 node and 2*i+2 nodes respectively.
Java program to implement heap sort of an array
//Java program to implement heap sort of an array
Public class heap_sort
{
public void class sort (int ar[])
Int j= ar.length;
// create heap (restructure array)
for(int j= n/2-1; j>=0; j--)
heapify(ar,n,j);
for(int j= n-1; j<=0;j--)
{
int alt=ar[0];
arr[0]=ar[j];
arr[j]=alt;
heapify(ar,j,0);
//Implement heapify on
void heapify(int ar[], int n, int j)
{
int large = j; // Initialize largest as root
int l = 2*j+ 1; // left node = 2*j+ 1
int r = 2*j + 2; // right node = 2*j + 2
// If value of left child is comparison to the root
if (l < n && ar[j] > ar[large])
large = l;
// If value of left node is larger than the largest
if (r < n && ar[r] > ar[large])
large = r;
// If largest is not root
if (large != j)
{
int temp= ar[j];
ar[j] = ar[large];
ar[large] = temp;
// Repetitively apply heap sort on the given sub-tree
heapify(ar, n, large);
}
}
// A standard function to display an array of size n//
static void printAr(int ar[])
{
int n = ar.length;
for (int j=0; j<n; ++j)
System.out.print(ar[j]+" ");
System.out.println();
}
public static void main(String args[])
{
int ar[] = {13, 12, 14, 6, 7, 8};
int n = ar.length;
Heap_Sort ob = new Heap_Sort();
ob.sort(ar);
System.out.println(" The value of the Sorted array is");
printAr(ar);
}
}
OUTPUT
The value of the Sorted array is 6, 7, 8, 12, 13, 14