I'm trying to implement a array based Heap Sort, its sorting the first few but not fully and I can't figure out why. Here is what I'm working with:
public class HeapSort{
static int[] numbers = new int[] { 0, 13, 8, 5, 10, 9, 15, 1, 2, 3, 6, 4, 12, 14, 7, 11 };
static int[] array = new int[16];
public static void main(String[] args) {
for (int i = 0; i < 15; i++) {
array[i] = numbers[i];
if (i > 1)
sort(i);
}
for (int i = 1; i < 15; i++) {
System.out.println(array[i]);
}
}
public static void sort(int i) {
int parentLocation = i / 2;
int childLocation = i;
int parentValue = array[parentLocation];
int childValue = array[childLocation];
if (childValue < parentValue) {
array[parentLocation] = childValue;
array[childLocation] = parentValue;
sort(parentLocation);
}
}
}
I'm sure that its a fault in my use of recursion to recall the sort on the parent but I can't see why?
TIA
I have this min heap implementation in c#, pretty easy to read. Your impl is missing a lot. such as heapify. Take a look at it. hope it helps.