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?