Preface: This isn't for homework, but it is for a "coding challenge", it's not worth any points in my course but i would like a fuller understanding of arrays and loops so i want this to work before i move on in the course.
So here's my problem. I'm trying to design a method that reverse sorts an array and places the numbers from highest to lowest. The code i have now is :
public static void selectionReverseSort (int[] array)
{
int startScan, index, maxIndex, maxValue;
for (startScan = 0; startScan < (array.length - 1); startScan++)
{
maxIndex = startScan;
maxValue = array[startScan];
for(index = startScan + 1; index < array.length; index++)
//index is 1
{
if (array[index] > maxValue)
{
maxValue = array[index];
//maxValue now becomes the second array number
maxIndex = index;
//maxIndex becomes the current index number.
}
array[maxIndex] = array[startScan];
array[startScan] = maxValue;
}
}
}
The problem with this code, is that it seems to only reverse sort the arrays if they were in ascending order to start with, otherwise it just repeats the highest number for the first few array slots. Anyone wanna help me understand what's going on here and what i could do to fix this?
Comparator
(and then you should be able swap from an ascendingComparator
to a descendingComparator
or the other way around). – Elliott Frisch 14 hours ago<
to>
, or vice versa, when comparing elements. If the algorithm for a reverse sort isn't right, the algorithm for a normal sort isn't going to be right either. – ajb 13 hours ago