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];
                position--;

            }
            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.

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?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.