简体   繁体   中英

Java fast way to add and sort lists

I have the following code for sorting moves in a board game. It looks to me like it can be highly optimized:

    private List<Move> sortMoves(List<Move> moves, int depth)
    {
        List<Move> sorted = new ArrayList<Move>();

        if (moves.size() == 0)
            return sorted;

        List<Move> primary = new ArrayList<Move>();
        List<Move> rest = new ArrayList<Move>();

        for(int i = 0; i < moves.size(); i++)
        {
            if (killers.primary[depth] != null && moves.get(i).equals(killers.primary[depth]))
                primary.add(moves.get(i));          

            else
                rest.add(moves.get(i));
        }

        sorted.addAll(primary);
        sorted.addAll(rest);

        return sorted;
    }

Is there a better and more efficient way to the above (ie. intersect the two lists and return a sorted list)?

Note: The goal of the function is to remove the killer moves (primary) found in the moves list and then return a new list with the killer moves first followed with what's list from the original moves list.

If your moves is not too big the current implementation looks ok. Its complexity is O(n). Only con here is the space complexity due to three extra lists viz. primary , rest and sorted .

You can save some space complexity by using Collections.sort(List<T> list, Comparator<? super T> c) .

private void sortMoves(final List<Move> moves, final int depth)
{
    Collections.sort(moves, new Comparator<Move>() {
        @Override
        public int compare(Move o1, Move o2) {

            if(killers.primary[depth] != null && moves.get(i).equals(killers.primary[depth])) {

                return 0;
            } else {

                return 1;
            }
        }
    });       
}

This doesn't use any extra space but has time complexity of O(nlog(n)). Additionally, its the implementation is concise.

UPDATE: Following is another elegant solution with no extra space complexity and O(n) time complexity.

private void sortMoves(final List<Move> moves, final int depth)
{

    int i = 0;
    int j = moves.size() - 1;

    while(i < j) {

        while(equalsKillersPrimary(moves.get(i), depth))
            i++;

        while(!equalsKillersPrimary(moves.get(j), depth))
            j--;

        swap(moves, i, j);
    }
}

private boolean equalsKillersPrimary(Move move, int depth) {

    return killers.primary[depth] != null && move.equals(killers.primary[depth]);
}

I've left out implementation of swap() for brevity. It simply swaps elements on the given indicies.

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