0
public static int[] bubbleSort(int[] inputArray){

        for(int i = 0; i < inputArray.length  - 1; i++ ){

            int tempa = inputArray[i];
            int tempb = inputArray[i + 1];

            if(inputArray[i] > inputArray[i + 1]){
                inputArray[i] = tempb;
                inputArray[i + 1] = tempa;
                i = 0;
                System.out.println(Arrays.toString(inputArray));
            }
        }
        return inputArray;
}

This implementation takes [20, 35, -15, 7, 55, 1, -22] and returns [20, -22, -15, 1, 7, 35, 55]. Sorts everything but the first index.

1
  • I'm new to Java. What I see here is that in worst case scenario the loop will restart for each element, hence n squared. Isn't that a bubble sort? Commented Sep 17, 2019 at 17:04

1 Answer 1

1

Why ... skips the first index?

Because you set i = 0 inside the loop, but then the loop will do i++, so the first element is only examined on the first iteration, not on any "restart".

To restart correctly, use i = -1 so the i++ will make restart happen at i = 0, not at i = 1.

That will make the code work, but it is inefficient to restart immediately upon swapping two elements, because you will repeatedly recheck the beginning of the array.

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

2 Comments

Isn't that the definition of bubble sort? It's inefficient and and it checks the array n squared times. Do you have any other implementation of bubble sort so I could compare.
I thought I had provided a link in a comment to the question, but I guess somebody deleted that. Try a web search for bubble sort, and look at e.g. the Wikipedia article. or the GeeksforGeeks article.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.