Reputation: 67
My question is if I wanted to change my sorting methods to sort in descending order what would have to be done? (Studying for a final)
My methods are as follows
public void selectionsort(Comparable[] array) {
for (int i = 0; i < array.length; i++) {
int min = i;
for (int j = i + 1; j < array.length; j++) {
if (array[j].compareTo(array[i]) < 0) {
min = j;
}
}
swap(array, min, i);
}
}
public void bubblesort(Comparable[] array) {
for (int poss = array.length; poss > 0; poss--) {
for (int i = 0; i < poss; i++) {
if (array[i].compareTo(array[i + 1]) > 0) {
swap(array, i, i + 1);
}
}
}
}
public static void insertionsort(Comparable[] array) {
for (int i = 1; i < array.length; i++) {
Comparable temp = array[i];
int poss = 0;
while (poss > 0 && array[poss - 1].compareTo(temp) > 0) {
array[poss] = array[poss - 1];
poss--;
}
array[poss] = temp;
}
}
I originally thought all that would need to be done is to change my compare to the opp of what is org was. But that does not seem to work.
Upvotes: -2
Views: 70
Reputation: 117
Create compareToReversed method that will return -compareTo result. Have a look here for inspiration
Upvotes: 0
Reputation: 2574
Write a comparator function and use it instead of the <
or >
symbol. Then you can control which order it's sorted in from the comparator.
Also you can have a parameter in the comparator that decides which way it sorts, and then take that as user input. So the way it gets sorted can be controlled from the command line.
Upvotes: 1
Reputation: 394006
Change array[j].compareTo(array[i]) < 0
to array[j].compareTo(array[i]) > 0
.
And similarly flip <
to >
(and vice versa) in all your compareTo
calls to reverse the order.
Upvotes: 2