I currently have 2 arrays, power and energy:
int[] power = [20, 10, 50, 10, 30, 5];
powerIndex 0 1 2 3 4 5
int[] energy = [20, 5, 15, 3, 10, 30];
energyIndex 0 1 2 3 4 5
I would like get an array with the indices of the power array sorted (lowest to highest), and in case the power number is the same, the power that uses less energy should get the first spot. So basically my desired output would be:
int[] result = [5, 3, 1, 0, 4, 2]
This is my code so far:
int[] result = new int[power.length];
int answerIndex = 0;
int tempSmallest = Integer.MAX_VALUE;
int lastNumberSaved = 0;
int posWithSmallerPower = 0;
while (answerIndex < power.length) {
for (int i = 0; i < power.length; i++) {
int current = power[i];
if (tempSmallest > current && current > lastNumberSaved) {
tempSmallest = current;
posWithSmallerPower = i;
}
if (tempSmallest >= current && current > lastNumberSaved) {
if (current != lastNumberSaved && energy[posWithSmallerPower] > energy[i]) {
tempSmallest = current;
posWithSmallerPower = i;
}
}
}
answer[answerIndex] = posWithSmallerPower;
answerIndex++;
lastNumberSaved = tempSmallest;
tempSmallest = Integer.MAX_VALUE;
}
return answer;
What i'm getting: [5, 3, 0, 4, 2, 2]. And again, what I'm supposed to get: [5, 3, 1, 0, 4, 2]
I'm having trouble dealing with the powers that have the same number. I do compare them in the second array by their energy and I actually get the power in the index 3 first, but then the code completely forgots about the second power that also had the same number (10).
How do I achieve this? Thank you!