I am working on a personal project to test heapsort on a group of objects. I am using HS to organize a set of students. using the example of a school project I already did using Selection sort I put this code together:
public static void heapify(Student[] studentList, int i, int size)
{
int right = 2*i+2;
int left = 2*i+1;
Student leftStudent = studentList[left];
Student rightStudent = studentList[right];
int max;
if(left <= size && leftStudent.getGrades() > studentList[i].getGrades())
max = leftStudent.getGrades();
else
max = studentList[i].getGrades();
if(right <= size && rightStudent.getGrades() > studentList[max].getGrades())
max = rightStudent.getGrades();
if(max != studentList[i].getGrades())
{
switchNodes(studentList, i, max);
heapify(studentList, max, size);
}
}
I already checked to see whether I have the right helper code in other parts and I do. I keep getting an
ArrayOutofBounds Error
at the code where I call this method.
How do I successfully implement the algorithm using the Student Object calls?
PS: Helper code as follows
public static void makeHeap(Student[] studentList)
{
for(int i = studentList.length/2; i>=0; i--)
heapify(studentList, i, studentList.length-1);
}
public static Student[] heapSort(Student[] studentList)
{
makeHeap(studentList);
int sizeOfHeap = studentList.length-1;
for(int i = sizeOfHeap; i>0; i--)
{
switchNodes(studentList, 0, i);
sizeOfHeap--;
heapify(studentList, 0, sizeOfHeap);
}
return studentList;
}
public static void switchNodes(Student[] studentList,int i, int j)
{
Student temp = studentList[i];
studentList[i] = studentList[j];
studentList[i] = temp;
}