I am working on bubblesort and came up with this code after studying. Almost every code on the web is different than mine. But mine works with no problem.
Can you guys tell me if I am doing it wrong?
int[] a= {23,1,5,12,1,2,3};
for (int i=0; i<a.length; i++) {
for (int j=1; j<a.length; j++) {
if(a[j]<a[j-1]) {
int temp=a[j];
a[j]=a[j-1];
a[j-1]=temp;
}
}
System.out.println(Arrays.toString(a));
}
According to the documentation by Corman :
"It works by repeatedly by swapping adjacent elements that are out of order", which yours does as well.
As mentioned in the book its not the most optimal solution, but it does so in O(n^2) time. How you implement is totally upto you, but If I were to grade it, I would give you full credit!