Reputation: 17
public static void mystery1(ArrayList<Integer> list) {
for (int i = list.size() - 1; i > 0; i--) {
if (list.get(i) < list.get(i - 1)) {
int element = list.get(i);
list.remove(i);
list.add(0, element);
}
}
System.out.println(list);
}
I'm trying to solve the for the output of this method with given sets of ArrayList values
. After looking over it, I was pretty sure this code would relocate the smaller value of a pair in the front of the list. I used an ArrayList of values [2, 6, 1, 8]
for input and the result was [1, 2, 6, 8]
, which was as I expected. But for [30, 20, 10, 60, 50, 40]
it produced [10, 30, 40, 20, 60, 50]
when I expected [40,50,10,20,30,60]
. Therefore can anyone please explain to me how this code actually processes the Arraylist
? Thanks!
Upvotes: 0
Views: 4143
Reputation: 1168
As the comments on your questions already stated, it looks like this algorithm does not do what it was made for. This can of course only be verified with the designer of the original code ;).
Now to give a short idea on what the code does, I've put the intermediate list results for each iteration below. The first position (before the colon) is the value of the index in the iteration.
// index 6, number 40 is less than 50, so 40 moves to the start of the list
result: 40 30 20 10 60 50
// index 5, number 60 is greater than 10, no changes made to the list
result: 40 30 20 10 60 50
// index 4, number 10 is less than 20, so 10 moves to the start of the list
result: 10 40 30 20 60 50
// index 3, number 30 is less than 40....
result: 30 10 40 20 60 50
// index 2, number 10 is less than 30....
result: 10 30 40 20 60 50
et voila, there is your result.
Upvotes: 0
Reputation: 152
Here is what happens, step by step:
The result is then: [10, 30, 40, 20, 60, 50]
Upvotes: 1
Reputation: 16185
I think you are forgetting that the loop is going from the end of the list to the beginning. If you take the list you gave as input and follow the process you will get the result [10, 30, 40, 20, 60, 50]. Which is the right one. Just do it in paper and you will see.
Upvotes: 0