I am trying to switch the below code to sort in descending order rather than ascending. It works when counting upwards, but nothing I try helps with getting it to count starting with the largest number and count downward.

public static void insertionSort(Comparable[] list) {
        for (int index = 1; index < list.length; index++) {
            Comparable key = list[index];
            int position = index;

That is the ascending part which works, and the while loop follows.

while (position > 0 && key.compareTo(list[position - 1]) < 0) {
                list[position] = list[position - 1];

            list[position] = key;


Couldn't I just change something in the while condition to change the direction it counts, I have tried for an hour and nothing has worked.

4 Years
Discussion Span
Last Post by ~s.o.s~

Think about which piece of code (or specifically which method call) in your above snippet is responsible for doing the comparisons. Read up on the Javadocs of the Comparable.compareTo method. Anything you see in there which can "reverse" the checks you are making?

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.