I have to sort an array using a sorting algorithm and show in which index the values were originally placed. (see expected result vs actual result: https://i.imgur.com/GpIpkPE.png).
I managed to sort correctly the values. BUT the index is HALF correct? Which is confusing me.
public static void sortNumbers(double[] averageNotes) {
for (int i = 0; i < averageNotes.length; i ) {
double max = averageNotes[i];
int maxId = i;
for (int j = i 1; j < averageNotes.length; j ) {
if (averageNotes[j] > max) {
max = averageNotes[j];
maxId = j;
}
}
double temp = averageNotes[i];
averageNotes[i] = max;
averageNotes[maxId] = temp;
System.out.println(averageNotes[i] " (" maxId ")");
}
Any help is highly appreciated. Thank you.
CodePudding user response:
Use an extra array for your indices and sort simultaneously:
public static void sortNumbers(double[] averageNotes) {
//create an array for your indices
int[] indices = new int[averageNotes.length];
//fill indices
for (int i = 0; i < averageNotes.length; i ) {
indices[i] = i;
}
//sort both arrays simultaneously
for (int i = 0; i < averageNotes.length; i ) {
for (int j = i 1; j < averageNotes.length; j ) {
if (averageNotes[i] < averageNotes[j]) {
double temp = averageNotes[i];
averageNotes[i] = averageNotes[j];
averageNotes[j] = temp;
int t = indices[i];
indices[i] = indices[j];
indices[j] = t;
}
}
}
//print
for (int i = 0; i < averageNotes.length; i ) {
System.out.println(averageNotes[i] " (" indices[i] ")");
}
}