I have this code for heapSort
which works fine. I also understand how the algorithm
works when the start index
is 1
and not 0
. My question is that the maxheap
method by itself below works for all indices greater than zero, but not at index 0. however the Sort
method calls with index 0
and the array
gets sorted
. when index i = 0
, the call to maxheap
will have left=2*i=0 and right=2*i+1=1
, which leads to i
and left
being same at 0
and right
at index 1
, meaning that the the root
and left
are same and has only right
tree. this is confusing to me. Here is the code:
public class HeapSort
{
private static int heapSize;
/* Sort Function */
public static void sort(int arr[])
{
heapify(arr);
System.out.println("arrays is "+Arrays.toString(arr));
for (int i = heapSize; i > 0; i--)
{
swap(arr,0, i);
heapSize = heapSize-1;
maxheap(arr, 0);
}
}
/* Function to build a heap */
public static void heapify(int arr[])
{
heapSize = arr.length-1;
for (int i = heapSize/2; i >= 0; i--)
maxheap(arr, i);
System.out.println("finished maxheap");
}
/* Function to swap largest element in heap */
public static void maxheap(int arr[], int i)
{
//heapSize = arr.length-1;// comment this out if you use sort method since `heapSize` is defined at heapfy method
int left = 2*i ;
int right = 2*i + 1;
int max = i;
if (left <= heapSize && arr[left] > arr[i])
max = left;
if (right <= heapSize && arr[right] > arr[max])
max = right;
//System.out.printf("i is %s; left is %s; right is %s; max is %s%n",i,left,right,max);
if (max != i)
{
swap(arr, i, max);
maxheap(arr, max);
}
}
/* Function to swap two numbers in an array */
public static void swap(int arr[], int i, int j)
{
//System.out.println("called");
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
/* Main method */
public static void main(String[] args)
{
System.out.println("Heap Sort Test\n");
/* Call method sort */
int[] arr = {34,5,6,712,90};
sort(arr);
System.out.println("\nElements after sorting ");
System.out.println(Arrays.toString(arr));
/* Call method maxheap; make sure you comment in heapSize=arr.length in the method */
int[] arr2 = {2,1,3};
maxheap(arr2, 1);
//maxheap(arr2,0) will not work, i.e gives same arr2 as output
System.out.println(Arrays.toString(arr2));
}
}
EDIT:
These two blogs uses the same code:
sanfoundry.com/java-program-implement-heap-sort,
sciencetechpedia.blogspot.com/2012/11/heap-sort-using-java.html