Search code examples
javasortingrecursionmergesort

why is my merge sort only sorting up to 4 elements in java


I'm trying to sort the names of patient into the view list, where it displays the lists of patients sorted alphabetically. However after using the merge sort (required), it only sorts up to four elements before it overwrites the other names. Also it would be helpful if I can link the sickness to the patients when sorting.

I tried using the merge sort which was required and after following the steps, the merge sort malfunctioned and did not display the names correctly. when there are under 3 elements, the sort would function normally, but if there are more than three it will overwrite the others.

Here's my code:

public static void mergeSort(ArrayList<String> a, Integer from, Integer to)
{
    if(from == to)
    {
        return;
    }
    Integer mid = (from + to)/2;
    mergeSort(a, from, mid);
    mergeSort(a, mid+1, to);
    merge(a, from, mid, to);
}

public static void merge(ArrayList<String> a, Integer from, Integer mid, Integer to)
{
    Integer n = to - from + 1;
    ArrayList<String> b =  new ArrayList<>(n);
    Integer i1 = from;
    Integer i2 = mid +1;
    Integer j = 0;
    while(i1<= mid && i2 <= to)
    {
        if(a.get(i1).compareTo(a.get(i2))<0)
        {
            b.add(a.get(i1));
            i1++;
        }
        else
        {
            b.add(a.get(i2));
            i2++;
        }
        j++;
    }
    while (i1 <= mid)
    {
        b.add(a.get(i1));
        i1++;
        j++;
    }
    while (i2 <= to)
    {
        b.add(a.get(i2));
        i2++;
        j++;
    }
    for(j = 0; j< n; j++)
    {
        a.add(from+j, b.get(j));;
    }
}

Solution

  • You should use set, not add in the final step. If you tried to debug the merge procedure and watched the "a" contents, you would see that it grows at each merge.

    for(j = 0; j< n; j++)
    {
        a.set(from+j, b.get(j));;
    }
    

    Also, in Java, it's considered a good style to program to interfaces, not concrete classes, so you might want to replace ArrayList with List in variable declarations.