I'm attempting to write a heapsort method in java but it's not working exactly as I want it to:
public class HeapSort {
private static int n;
private static void swap(int[] A, int a, int b)
{
int tmp = A[a];
A[a] = A[b];
A[b] = tmp;
}
private static void insert(int[] A, int i)
{
int left = i * 2;
int right = left + 1;
int max = i;
if (left <= n && A[left] < A[max]){
max = left;
}
if (right <= n && A[right] > A[max]) {
max = right;
}
if (max != i) {
swap(A, i, max);
insert(A, max);
}
}
public static void HeapSort(int[] A)
{
n = A.length - 1;
for (int i = n / 2; i >= 0; i--)
insert(A, i);
for (int i = n; i > 0; i--) {
swap(A, 0, i);
n--;
insert(A, 0);
}
}
public static void main(String[] args){
int[] A = new int[] {9, 2, 8, 1, 4};
System.out.println(java.util.Arrays.toString(arr));
HeapSort(A);
System.out.println(java.util.Arrays.toString(arr));
}
}
It works with some arrays however arrays like 9, 2, 8, 1, 4 will get sorted into 1, 4, 2, 8, 9. So why isn't it sorting the array in the correct way?
Try this and see. I have made the complete program as below. This works fine for input you provided.
}
Here is the output.
If you define
left = i * 2
, the root of your heap should be stored inA[1]
, notA[0]
. By not using the array at index0
, you can always say that the left and right children of a nodei
are2*i
and2*i+1
, respectively.Basically, in your
HeapSort
, you should change 0 to 1 (there are 4 of them). Test it with array{0, 9, 2, 8, 1, 4}
.And also, a comparison in
insert
is also wrong. It should beA[left] > A[max]
.