Open In App

C Program For Bubble Sort

Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will learn about the bubble sort algorithm and how to write the bubble sort program in C. We will also look at the working of bubble sort in C and the optimized C program that improves the performance of bubble sort.

What is Bubble Sort?

Bubble sort is a simple sorting algorithm that works by comparing the adjacent elements in the list and swapping them if the elements are not in the specified order. It is an in-place and stable sorting algorithm that can sort items in data structures such as arrays and linked lists.

Bubble Sort Algorithm in C

The algorithm to sort data of the list in increasing order using bubble sort in C is:

  • Run two loops nested in one another.
     
  • The outer loop will run from i = 0 to i < n – 1, where n is the number of elements in the list.
     
  • The inner loop will run from j = 0 to j < n – i – 1. It is because, after each iteration of the outer loop, one element at the end (or at the start if the order is decreasing order) will be in its right place so we can leave it as it is.
     
  • In the inner loop, we will check if the arr[ j ] > arr[ j + 1 ].
    • If it’s true, then we will swap places of these elements.
    • If false, we will continue to the next iteration.
       
  • This process will be repeated till the conditions of the loop are satisfied.

For decreasing order,

  • The inner loop will run from j = i to j < n – 1.
  • We will compare the elements as arr[ j ] < arr[ j + 1 ].

Everything else will be the same.

Bubble Sort Program in C

C




// C program for implementation of Bubble sort
#include <stdio.h>
 
// Swap function
void swap(int* arr, int i, int j)
{
    int temp = arr[i];
    arr[i] = arr[j];
    arr[j] = temp;
}
 
// A function to implement bubble sort
void bubbleSort(int arr[], int n)
{
    int i, j;
    for (i = 0; i < n - 1; i++)
 
        // Last i elements are already
        // in place
        for (j = 0; j < n - i - 1; j++)
            if (arr[j] > arr[j + 1])
                swap(arr, j, j + 1);
}
 
// Function to print an array
void printArray(int arr[], int size)
{
    int i;
    for (i = 0; i < size; i++)
        printf("%d ", arr[i]);
    printf("\n");
}
 
// Driver code
int main()
{
    int arr[] = { 5, 1, 4, 2, 8 };
    int N = sizeof(arr) / sizeof(arr[0]);
    bubbleSort(arr, N);
    printf("Sorted array: ");
    printArray(arr, N);
    return 0;
}


Output

Sorted array: 
1 2 4 5 8 





Complexity Analysis of Bubble Sort

Time Complexity: O(N2), where N is the number of items in the list.
Auxiliary Space: O(1)

Working of Bubble Sort in C

The Bubble sort algorithm works by comparing the adjacent elements and swapping them if they are in the wrong order.

First Pass

Algorithm compares the first two elements

   5   

   1   

   4   

   2   

   8   

  • Swaps since 5 > 1.

   1   

   5   

   4   

   2   

   8   

  • Swap since 5 > 4.

   1   

   4   

   5   

   2   

   8   

  • Swap since 5 > 2.

   1   

   4   

   2   

   5   

   8   

  • Now, since these elements are already in order (8 > 5), algorithm does not swap them.

Second Pass

Now, during the second iteration arr should look like this

   1   

   4   

   2   

   5   

   8   

  • No Swapping since 1 < 4.

   1   

   4   

   2   

   5   

   8   

  • Swap since 4 > 2.

   1   

   2   

   4   

     

   8   

  • No Swapping since 4 < 5.

The array is already sorted, but the algorithm will still move to the third pass

Third Pass

The algorithm needs one whole pass without any swap to know it is sorted.

   1   

   2   

   4   

   5   

   8   

  • No Swapping since 1 < 2.

   1   

   2   

   4   

   5   

   8   

  • No swapping since 2 < 4.

Again, we will move to the fourth pass even when the array is sorted.

Fourth Pass

There will be only one comparison in the fourth pass and no swap will be done as 1 < 2.

   1   

   2   

   4   

   5   

   8   

Optimized Bubble Sort Program in C

As we have seen in the above example that the bubble sort algorithm still completed the third and fourth passes even when the array was sorted in the second pass. We can improve the code to prevent such cases. In the optimized program for bubble sort:

  • A new variable swapped is used to signal if the swap operation is done in the inner loop iteration.
  • If the swap doesn’t occur in the iteration, it means that the array is already sorted.

C




//  C Program with Optimized implementation of Bubble sort
#include <stdbool.h>
#include <stdio.h>
 
// Swap function
void swap(int* a, int* b)
{
    int temp = a;
    a = b;
    b = temp;
}
 
// An optimized version of Bubble Sort
void bubbleSort(int arr[], int n)
{
    // swapped variable to signal if there is a
    // swap happened in the inner loop
    // initially set to false
    for (int i = 0; i < n - 1; i++) {
        // swapped is initialized as false at the start
        bool swapped = false;
        for (int j = 0; j < n - i - 1; j++) {
            if (arr[j] > arr[j + 1]) {
                swap(arr + j, arr + j + 1);
                // swapped is set to true if the swap is
                // done
                swapped = true;
            }
        }
 
        // If no two elements were swapped
        // by inner loop, then break
        if (swapped == false)
            break;
    }
}
 
// Function to print an array
void printArray(int arr[], int size)
{
    int i;
    for (i = 0; i < size; i++)
        printf(" %d", arr[i]);
}
 
// Driver code
int main()
{
    int arr[] = { 5, 3, 1, 9, 8, 2, 4, 7 };
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // bubbleSort function called
    bubbleSort(arr, N);
 
    printf("Sorted array: ");
    printArray(arr, N);
    return 0;
}


Output

Sorted array:  1 2 3 4 5 7 8 9





Note: Although this approach improves the performance of bubble sort in some cases, it does not change its worst case time complexity.

To know more about bubble sort, please refer to the article – Bubble Sort – Data Structure and Algorithm Tutorials



Last Updated : 07 Mar, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads