Search code examples
javasortingarraylistmergesort

Merge Sort not working


I have an ArrayList of objects which I'm trying to sort by a 'saving'number stored in the object. My code so far is written below

public static void mergesort(ArrayList<Object> list){
    if(list.size() > 1){
        //Split the list in half and create an ArrayList for each side 
        int q = list.size()/2;
        //System.out.println(list.size() + " " + q);
        ArrayList<Object> leftList = new ArrayList<Object>();
        for(int i = 0; i > q; i++){
            leftList.add(list.get(i));
        }
        ArrayList<Object> rightList = new ArrayList<Object>();
        for(int j = q; j < list.size(); j++){
            rightList.add(list.get(j));
        }
        //  System.out.println(" leftList " + leftList.size() + " rightList " + rightList.size());
        //sort each half of the list
        //note: this will happen recursively
        mergesort(leftList);
        mergesort(rightList);
        merge(leftList, rightList, list);
    }
}
public static void merge(ArrayList<Object> leftList, ArrayList<Object> rightList, ArrayList<Object> list){
    //'i' stores the index of the main array
    //'l' stores the index of the left array
    //'r' stores the index of the right array
    int i = 0, l = 0, r = 0;
    //the loop will run until one of the arraylists becomes empty
    while(leftList.size() != l && rightList.size() !=r){
        //if the saving of the current element of leftList is less than the rightList saving
        if(leftList.get(l).getSaving() < rightList.get(r).getSaving()){
            //Copy the current element into the final array
            list.set(i, leftList.get(l));
            i++;
            l++;
        }
        else {
            list.set(i, rightList.get(r));
            i++;
            r++;
        }
    }

    while(leftList.size() != l){
        list.set(i, leftList.get(l));
        i++;
        l++;
    }

    while(rightList.size() != r){
        list.set(i,rightList.get(r));
        i++;
        r++;
    }


}

For some reason when I run it I don't get any errors, however, the list remains unsorted. any advice would be much appreciated. Thanks in advance


Solution

  • The problem is in the first for of the mergesort method:

    for (int i = 0; i > q; i++) {

    It should be:

    for (int i = 0; i < q; i++) {

    Checkout the condition..