Heap Sort - Java
import java.util.*;
class Sort
{
int a[],n,ne;
Scanner s=new Scanner(System.in);
void read()
{
System.out.println("Enter number of elements...");
n=s.nextInt();
ne=n;
a=new int[n];
System.out.println("Enter the elements..");
for(int i=0;i<n;i++)
a[i]=s.nextInt();
}
void display()
{
System.out.println("Sorted List..");
for(int i=0;i<n;i++)
System.out.println(a[i]);
}
void heapsort()
{
//build heap structure
buildheap();
//extract maxima
extractmax();
}
void buildheap()
{
//let heap grow from half size to entire size
for(int i=n/2-1; i>=0; i--)
{
heapify(i,n);
}
}
void extractmax()
{
//n is separator between heap and sorted part
while (ne>1)
{
ne--;
//put maximum at the end of heap
swap(0,ne);
//restore heap
heapify(0,ne);
}
}
//restore heap invariant
void heapify(int i, int n)
{
int k=2*i+1; //first child of i
while (k<n)
{
//if another child exists and that child is the maximum
if (k+1<n && a[k+1]>a[k]) k++;
if (a[i]>=a[k])
{
return; //heap invariant restored
} else
{
//swap element with its child
swap(i, k);
//continue with next iteration
i=k;
k=2*i+1;
}
}
}
void swap (int i, int j)
{
int t = a[i];
a[i] = a[j];
a[j] = t;
}
}
class Main
{
public static void main(String args[])
{
Sort s=new Sort();
s.read();
s.heapsort();
s.display();
}
}
Comments
Post a Comment