合并排序不起作用

时间:2015-10-29 18:12:02

标签: java sorting arraylist mergesort

我有一个对象的ArrayList,我试图通过存储在对象中的'保存'数字来排序。到目前为止我的代码写在下面

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++;
    }


}

由于某些原因,当我运行它时,我没有收到任何错误,但是,列表仍未排序。任何建议将不胜感激。提前致谢

1 个答案:

答案 0 :(得分:1)

问题出在mergesort方法的第一个问题:

  

for(int i = 0; i&gt; q; i ++){

应该是:

  

for(int i = 0; i&lt; q; i ++){

检查条件..