Need explanations on how this code processes Arraylist values

前端 未结 3 1963
迷失自我
迷失自我 2021-01-27 07:00
public static void mystery1(ArrayList list) { 
for (int i = list.size() - 1; i > 0; i--) { 
    if (list.get(i) < list.get(i - 1)) { 
        int el         


        
3条回答
  •  甜味超标
    2021-01-27 07:16

    Here is what happens, step by step:

    • Initial state of your list: [30, 20, 10, 60, 50, 40]
    • Is 40<50? Yes. So remove 40, and put it as the first element of the list: [40, 30, 20, 10, 60, 50]
    • Is 60<10? No. don't touch anything: [40, 30, 20, 10, 60, 50]
    • Is 10<20? Yes. So remove 10, and put it as the first element of the list: [10, 40, 30, 20, 60, 50]
    • Is 30<40? Yes. So remove 30, and put it as the first element of the list: [30, 10, 40, 20, 60, 50]
    • Is 10<30? Yes. So remove 10, and put it as the first element of the list: [10, 30, 40, 20, 60, 50].

    The result is then: [10, 30, 40, 20, 60, 50]

提交回复
热议问题