1

In Java, using comparator, is it possible to sort elements at the specific positions in a list? If so, how? Example : the list {1,2,3,4,10,6,7,8} indices of elements to be sorted {3,4,7} in descending order, the result would be {1,2,3,10,8,6,7,4}.

2 Answers 2

1

Presumably you know the specific positions beforehand? If so, create a new list comprised of the elements you want to sort, sort the list, and then replace the elements in the original list with your sorted list, one element at a time.

Sign up to request clarification or add additional context in comments.

Comments

0

Would something like this work? You would construct the Comparator with a list of the values and the list of indexes to sort:

private static class MyComparator implements Comparator<Integer>{

        private ArrayList<Integer> indexes;
        private ArrayList<Integer> vals;
        public MyComparator(ArrayList<Integer> indexes, ArrayList<Integer> vals){
            this.indexes = indexes;
            this.vals = vals;
        }
        @Override
        public int compare(Integer arg0, Integer arg1) {

            if(indexes.contains(vals.indexOf(arg0)) && indexes.contains(vals.indexOf(arg1))){
                return Integer.compare(arg1, arg0); 
            }
            return 0;
        }

    }

2 Comments

This was what I tried, unfortunately it did not work.
I got output that seemed like what you expected. I guess I should have tried your specific example because I do see that it is different. Sorry!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.