I am new to Java and I have a question regarding optimization.
How fast is it if I declare before my IF statement a variable that gets the value of x.indexOf(i) + 1
instead of just putting it twice in my code below (which depicts the first call of a bubblesort, without the recurency).
Is it worth to actually make a j
variable which holds that x.indexOf(i) +1
instead of just letting the function run once more?
I also believe that my first condition in the IF is a bit flawed, is it possible to let the i
start at a i+1
value in a foreach?
Also the use of ArrayList is mandatory.
Thanks for the answers. (Haven't read yet the Coding Standard in Java so I guess it looks ugly)
public static void bubbleOnce(ArrayList<Integer> x) {
for(int i : x) {
if((x.indexOf(i) != x.size()-1) && i > x.get(x.indexOf(i) + 1)) {
Collections.swap(x, x.indexOf(i), (x.indexOf(i) + 1));
}
}
}
Using
indexOf
is not correct, if yourArrayList x
contains more than one value ofi
, your sort method will behave incorrectly.For example, this case:
[5, 5, 1]
After running your program, return
[5, 5, 1]
Plus, using
indexOf
, as mentioned by tucuxi, will slow down your program.