About sorting method in Java

  • Comp Sci
  • Thread starter lypaza
  • Start date
  • #1
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:
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 :confused:
 

Answers and Replies

Related Threads on About sorting method in Java

Replies
11
Views
11K
Replies
6
Views
2K
  • Last Post
Replies
0
Views
2K
  • Last Post
Replies
23
Views
3K
Replies
3
Views
1K
  • Last Post
Replies
11
Views
792
  • Last Post
Replies
1
Views
2K
Replies
3
Views
2K
  • Last Post
Replies
11
Views
3K
Replies
1
Views
4K
Top