What is wrong in my bubble sort in ArrayList? It was not sorted . I am a beginner.
public static ArrayList < Integer > bubbleSort(ArrayList < Integer > ar) {
for (int i = 0; i < ar.size() - 1; i++) {
int indexMax = i;
for (int j = 1; j < ar.size(); j++) {
if (ar.get(indexMax) > ar.get(j)) {
indexMax = j;
}
}
if (indexMax != i) {
int temp = ar.get(i);
ar.set(i, ar.get(indexMax));
ar.set(indexMax, temp);
}
}
return ar;
}
Your swapping code block looked like it was outside of loop, so the only one swap occurred for one iteration of main loop.
You are also doing unnecessary comparing of elements, starting your inner loop with precondition j = 1
. You should start it from i
, as after some iterations of outer loop range from 0 to i
will be already sorted.
I think you can use a simpler approach.
for (int i = 0; i < ar.size() - 1; i++) {
for (int j = i; j < ar.size(); j++) {
if (ar.get(j) < ar.get(i)) {
Integer temp = ar.get(j);
ar.set(j, ar.get(i));
ar.set(i, temp);
}
}
}
As you can see, swapping takes place inside of the inner loop, and it also skips already sorted part of collection.