Search code examples
javabubble-sort

Why is my bubble sort algorithm implementation sorting the entire array and skips the first index?


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.


Solution

  • 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.