Java program to print the heap sort algorithm using for loop

Java program to print the heap sort algorithm using for loop. Heap sorting software in java for a novice to learn advanced concepts like sorting in java sorting for beginners. This software is built around the heap concept. Heap sort is a sorting technique that uses a Binary Heap data structure to compare items. It’s similar to a selection sort, in which the minimum element is found first and then placed.

public class Main
{
public void sort(int arr[])
{
int n = arr.length;
for (int i = n / 2 - 1; i >= 0; i--)
heaper(arr, n, i);
for (int i=n-1; i>=0; i--)
{
int temp = arr[0];
arr[0] = arr[i];
arr[i] = temp;
heaper(arr, i, 0);
}
}
void heaper(int arr[], int n, int i)
{
int largest = i; 
int l = 2*i + 1; 
int r = 2*i + 2; 
if (l < n && arr[l] > arr[largest])
largest = l;
if (r < n && arr[r] > arr[largest])
largest = r;
if (largest != i)
{
int swap = arr[i];
arr[i] = arr[largest];
arr[largest] = swap;
heaper(arr, n, largest);
}
}
static void printArray(int arr[])
{
int n = arr.length;
for (int i=0; i<n; ++i)
System.out.print(arr[i]+" ");
System.out.println();
}
public static void main(String args[])
{
int arr[] = {33,45,56,78,87,64};
int n = arr.length;
Main ob = new Main();
ob.sort(arr);
System.out.println("Sorted array is");
printArray(arr);
}
}

 

Output:

Sorted array is 33 45 56 64 78 87