Bubble sort, print array per pass

Viewed 21

How can you print the array per iteration in Bubble sort? So far this is my sort function and im not really sure about it:

void sortBubble(int *arr)
{
    int i, j;
    int temp;
    for (i = 0; i < SIZE; i++)
    {
        for (j = i + 1; j < SIZE; j++)
        {
            if (arr[i] > arr[j])
            {
                temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;
            }
        }
    }
  
    printArr(arr); //call print function to print sorted array
}
1 Answers

If you want something to happen on each iteration of a loop, it should be placed within the loop body.

void sortBubble(int *arr)
{
    int i, j;
    int temp;
    for (i = 0; i < SIZE; i++)
    {
        for (j = i + 1; j < SIZE; j++)
        {
            if (arr[i] > arr[j])
            {
                temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;
            }
        }
  
        printArr(arr);
    } 
}

It's also advisable to minimize the scope of variables. i, j, and temp do not need to be scoped at the function level.

void sortBubble(int *arr)
{
    for (int i = 0; i < SIZE; i++)
    {
        for (int j = i + 1; j < SIZE; j++)
        {
            if (arr[i] > arr[j])
            {
                int temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;
            }
        }
  
        printArr(arr);
    } 
}

One final note: you can optimize your bubble sort by keeping track of the number of swaps performed in the inner loop. If zero swaps are performed you know the array is already sorted and you can immediately return.

Bubble sort is O(n^2) in the worst case. Your implementation is always O(n^2). This small change can reduce it to O(n) in the best case scenario, or in the realistic scenario, somewhere in between.

void sortBubble(int *arr)
{
    for (int i = 0; i < SIZE; i++)
    {
        int swaps = 0;

        for (int j = i + 1; j < SIZE; j++)
        {
            if (arr[i] > arr[j])
            {
                int temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;

                swaps++;
            }
        }

        printArr(arr);
       
        if (swaps == 0 /* or !swaps */) return;
    } 
}
Related