# Heapsort

**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

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

## Leave a comment

## Comments 0