简体   繁体   中英

Why does my sort method fail to sort some charachter?

So, this is my code:

public ArrayList<Actor> SortArray(ArrayList<Actor> actorsArrayList){
    if (actorsArrayList.size()==2){
        if (actorsArrayList.get(0).getName().compareTo(actorsArrayList.get(1).getName())>0){
            Actor tmpActor = actorsArrayList.get(0);
            actorsArrayList.set(0, actorsArrayList.get(1));
            actorsArrayList.set(1, tmpActor);
        }
    }if (actorsArrayList.size()>2){
        ArrayList<Actor> part1 = new ArrayList<Actor>    (actorsArrayList.subList(0, actorsArrayList.size()/2));
        ArrayList<Actor> part2 = new ArrayList<Actor>    (actorsArrayList.subList(actorsArrayList.size()/2, actorsArrayList.size()));
        SortArray(part1);
        SortArray(part2);
        actorsArrayList = MergeArrays(part1,part2);
    }
    return actorsArrayList;
}

public ArrayList<Actor> MergeArrays(ArrayList<Actor> part1, ArrayList<Actor> part2){
    ArrayList<Actor> mergedArray = new ArrayList<Actor>();
    int i = 0;
    int j = 0;
    while (i<part1.size() && j<part2.size()){
        if (part1.get(i).getName().compareTo(part2.get(j).getName())<0){
            mergedArray.add(part1.get(i));
            i=i+1;
        }else if (part1.get(i).getName().compareTo(part2.get(j).getName())>0){
            mergedArray.add(part2.get(j));
            j=j+1;
        }
    }

    while (i<part1.size()){
        mergedArray.add(part1.get(i));
        i=i+1;
    }
    while (j<part2.size()){
        mergedArray.add(part2.get(j));
        j=j+1;
    }
    return mergedArray;
}

This code is meant to be used with a huge ActorsArrayList, by using my own MergeSort method to sort it alphabetically (Actor class contains the parameter Name, which is the string I use to sort the array). I'm currently trying to make this method work with a very simple array that contains [d,a,b,l,z,x,y,c,w]. It works propperly but the "l" always goes to the end, no matter what the starting order is. If I try it out with the real actors arrayList (which contains real names) it doesn't really sort anything.

Thanks a lot for your help :)

Edit 1: Clarified code. I don't need the case where the size of the array I want to sort is 0 either, for some people commenting it.

Edit 2: There will never be 2 actors with the same name, because they would have been merged in a previous phase of my program.

The problem is in the actorsArrayList.size()>2 case of SortArray() . You are sorting each part into new ArrayList s but forgetting to use the sorted lists in your call to MergeArrays() . Fix like this:

        part1 = SortArray(part1);
        part2 = SortArray(part2);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM