0

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));
} 
1
  • I'm voting to close this question as off-topic because it's asking for input/review on working code. While off-topic here, it might be a fit for Code Review, but read A guide to Code Review for Stack Overflow users first. Commented Apr 27, 2017 at 21:45

2 Answers 2

1

This is technically correct but sub-optimal. The other solutions you are mentioning likely include a boolean value to ensure the list is not sorted already before going further. Your version will do O(n^2) iterations no matter what, even if the input is already sorted.

Sign up to request clarification or add additional context in comments.

Comments

0

According to the documentation by Corman :

https://books.google.com/books?id=aefUBQAAQBAJ&lpg=PA40&ots=dMbqQt0QiW&dq=Introduction%20to%20Algorithms%20corman%20bubble%20sort&pg=PA40#v=onepage&q=Introduction%20to%20Algorithms%20corman%20bubble%20sort&f=false

"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!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.