Search code examples
javasortingreverseselection-sort

How to reverse SelectionSort to display in descending order?


I am trying to create a selectionSort method to arrange values in descending order. This code arranges them in ascending order. How can I swap this code to arrange it the other way.

public void selectionSort()
{
    int n = data.length;

    for(int index = 0; index < n-1; index++)
    {
        int min_idx = index;
        for(int j = index+1; j < n; j++)
            if(data[j] < data[min_idx])
                min_idx = j;

        int temp = data[min_idx];
        data[min_idx] = data[index];
        data[index] = temp;
    }
}

Solution

  • As of now I can think of two methods. I haven't tried them but worth giving a try.

    1. Multiply all the numbers by -1 and apply the original selection sort to sort for ascending order. After sorting is complete multiply all the numbers by -1 to get back originwl numbers but now they are sorted in descending order.

    2. Try changing the comparison condition if(data[j] < data[min_idx])
      to if(data[j] >= data[min_idx])

    Let me know if there is some issue with these methods.