- #1
lypaza
- 18
- 0
I wrote a class to sort Comparable elements in a list (ArrayList)
I have Student class that contains lastName, firstName, studentID, and tuitionFee as its instance variables.
At first I used mergeSort algorithm to write the Sorts class. It works when I add 1 student, still works with 2 students, but when I add 3 students, the IndexOutOfBoundsException occurs.
Here is my code:
I was staring at it without blinking but still don't get it
I have Student class that contains lastName, firstName, studentID, and tuitionFee as its instance variables.
At first I used mergeSort algorithm to write the Sorts class. It works when I add 1 student, still works with 2 students, but when I add 3 students, the IndexOutOfBoundsException occurs.
Here is my code:
Code:
import java.util.*;
public class Sorts
{
public static void sort(ArrayList objects)
{
mergeSort(objects, 0, (objects.size()-1));
}
public static void mergeSort(ArrayList list, int start, int end)
{
if (start < end)
{
int mid = (int)Math.floor((start + end)/2);
mergeSort(list, start, mid);
mergeSort(list, mid+1, end);
merge(list, start, mid, end);
}
}
public static void merge(ArrayList list, int start, int mid, int end)
{
int firstLength = mid - start + 1;
int secondLength = end - mid;
Comparable [] first = new Comparable[firstLength];
Comparable [] second = new Comparable[secondLength];
for (int i = 0; i < firstLength; i++)
first[i] = (Comparable)list.get(i);
for (int i = 0; i < secondLength; i++)
second[i] = (Comparable)list.get(mid+1+i);
list.clear();
int i = 0;
int j = 0;
while ((i<firstLength) && (j<secondLength))
{
if ( first[i].compareTo(second[j]) < 0)
{
list.add(first[i]);
i++;
}
else
{
list.add(second[j]);
j++;
}
}
while (i < firstLength)
{
list.add(first[i]);
i++;
}
while (j < secondLength)
{
list.add(second[j]);
j++;
}
}
}
I was staring at it without blinking but still don't get it