Search code examples
javamethodscounterbubble-sort

Using a counter in bubble sort


The problem is to count how many times my bubble sort algorithm switches the places of numbers. I tried to use a variable which increments by one each time, but I think there may be an error with scopes or something similar. Instead of returning a number such as 6 (which means numbers were swapped 6 times), it returns 0, which is what I initialized my variable as. How would I get my program to work?

public static int sort(int arr[]) {
    int length = arr.length;
    int temp;
    int count = 0;
    for (int i = 0; i < (length); i++) {
        for (int j = 1; j < (length); j++) {
            if (arr[j - 1] > arr[j]) {
                temp = arr[j-1];
                arr[j-1] = arr[j];
                arr[j] = temp;
                count++;
            }
        }
    }
    return count;
}

Solution

  • Looks like your algorithm is not optimized because of your for loop condition and initialization. As a result you are comparing an element with itself which is redundant.

    Proper approach should be like below:

    int yourCounter = 0;
    for (int i = 0; i < length; i++)
     for (int j = 1; j < length-i; j++)
       if (arr[j - 1] > arr[j]) {
         //swap code
         //yourCounter++;
       }
    

    your counter should give you proper result then.