I would like to know how else I can optimize bubble sort so that it overlooks elements that have already been sorted, even after the first pass.
Eg. [4, 2, 3
I think this is what you need. The key is to consider the array only till the index where last swap occured(newn).
public static void bubblesort(int[] a) {
int i, n, newn;
n = a.length;
while (n > 0) {
newn = 0;
for (i = 1; i < n; i++) {
if (a[i - 1] > a[i]) {
temp = a[i];
a[i] = a[i - 1];
a[i - 1] = temp;
newn = i;
}
}
n = newn;
}
return a;
}