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;
}
}
As of now I can think of two methods. I haven't tried them but worth giving a try.
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.
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.