1. Not finding help here? Sign up for a free 30min tutor trial with Chegg Tutors
    Dismiss Notice
Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

About sorting method in Java

  1. Oct 25, 2007 #1
    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 (Text):

    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:
     
  2. jcsd
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Can you help with the solution or looking for help too?



Similar Discussions: About sorting method in Java
  1. JAVA indexOf() method (Replies: 0)

Loading...