Heapsort

The Code Vault

Java Code To Illustrate Heapsort:

 

package heapsort;

import edu.princeton.cs.introcs.*;

public class Heapsort
{

public static int heapsize;

public static int Parent(int i)
{
return i/2;
}

public static int Left(int i)
{
return 2*i+1;
}

public static int Right(int i)
{
return 2*i+2;
}

public static void MaxHeapify(int A[], int i)
{
int l = Left(i);
int r = Right(i);
int greatest,temp;
if (l<heapsize && A[l]>=A[i]) greatest = l;
else greatest = i;
if (r<heapsize && A[r]>=A[greatest]) greatest = r;
if (greatest!=i)
{
temp = A[greatest];
A[greatest] = A[i];
A[i] = temp;
MaxHeapify(A,greatest);
}
}

public static void BuildHeap(int A[], int n)
{
int i;
for (i=(n/2)-1;i>=0;i–) MaxHeapify(A,i);
}

public static void heapsort(int A[])
{
BuildHeap(A,heapsize);
int i,temp;
for (i=A.length-1;i>=1;i–)
{
temp = A[0];
A[0] = A[i];
A[i] = temp;
heapsize–;
BuildHeap(A,heapsize);
}
}

public static void displayheap(int A[])
{
int height = (int)((Math.log10(A.length)) / (Math.log10(2)));
int spaces =…

View original post 82 more words

Advertisements

About Khuram Ali

Programming... Programming and Programming...!!!

Posted on June 27, 2013, in Algorithms, Java and tagged . Bookmark the permalink. Leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: