Answer the question
In order to leave comments, you need to log in
The for loop doesn't work properly - why?
Hello. I am writing code that will check a one-dimensional array. This is actually necessary for the implementation of the game "fifteen". In general, there is an array for example 6, 11, 7, 15, 9, 4, 1, 14, 10, 5, 13, 3, 8, 0, 2, 12. I need the loop to take the first number (in this case 6) and compared it with the next numbers in the array and determined how many numbers less than 6 are after it. In this case, it is 5 numbers (from 1 to 5). Then he must take the trace of the number 11 and check in a similar way (only not counting 6, because it comes before even though it is less than 11). I think you understand. I am adding a piece of code.
PS I forgot to say that you need to count the number of inversions (the number of numbers after the first one) In our case, this is 5 and then add them all up.
int[] p = { 6, 11, 7, 15, 9, 4, 1, 14, 10, 5, 13, 3, 8, 0, 2, 12 };
int inversions = 0;
for(int i = 0; i < p.length; i++) {
for(int j = i + 1; j < p.length; j++) {
if(p[i] > p[j]) inversions++;
}
}
Answer the question
In order to leave comments, you need to log in
create an array for each int[] inversions number, and then in the inversions[i]++ loop;
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question