i want to implement a selection sort method that takes an array of ints and sorts it in a descending order. however, the trick is to keep the original selection sort method unchanged but instead using simple arithmetic operations and without adding extra loops to swap the elements after the array finished sorting. this is my code and the idea is to store the position of the maximum value and the minimum value in local variables and swap them with the corresponding position after the inner loop finishes iteration. i even tried using a only one variable to find the lowest value and put it at the end of the array but i failed and i am getting the wrong results and i need help spotting the error. here is my code
public static void newSortMethod(int[]a){
for(int i = 0; i < a.length-1; i++){
int maxPosition=i;
int minPosition=i;
for(int j = i+1; j < a.length; j++){
if(a[j] < a[minPosition]){
minPosition = j;
}
if(a[j] > a[maxPosition]){
maxPosition = j;
}
}
swap(a,maxPosition,i);
swap(a,minPosition,a.length-i-1);
}
System.out.println();
}
public static void swap(int[]a, int i, int j){
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
public static void main(String[] args) {
int[] a = {2,6,3,9,5,4,8,7,0,13,-3,1};
newSortMethod(a);
}
here is the output of the program so far -3 8 2 9 13 5 4 6 3 1 7 0
Your original algorithm is wrong. Firstly, the
if
blocks should compare tominPosition
andmaxPosition
, noti
. Secondly, if you are selecting both minimum and maximum, then your inner for loop should stop ata.length - i
, nota.length
(since the topi
elements are also sorted). Doing both gives you this as the ascending order algorithm.To switch to descending order, simply add one line.
Errors
First off, let’s look for problems in your code. There’s a few, which happens a lot in programming.
swap(a,minPosition,i)
, and then trying to put the maximum value at the end, which isn’t what you want: you want to put maximum values at the beginning.n
is never modified, so you’ll keep printing0
.Sample solution
Now let’s see something that works. I’m not totally sure what your ascending selection sort looked like, but I imagine it should be something like this:
To make it sort in descending order, just switch the comparison operator (and possibly the
minPosition
identifier for clarity).