Open In App

C Program For Bubble Sort

Last Updated : 27 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

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

In this article, we will learn how to implement bubble sort algorithm in a C program.

Bubble Sort Algorithm

Follow the below approach to implement bubble sort algorithm in C. It is modified for increasing order, but you can change it easily for any desired order.

  • Compare and swap the adjacent elements if they are in the wrong order starting from the first two elements.
  • Do that for all elements moving from left to right. We will get the largest element at the right end.
  • Start compare and swap again from the start but this time, skip the last element as its already at correct position.
  • The second last element will be moved at the right end just before the last element.
  • Repeat the above steps till all the elements are sorted.

C Program to Implement Bubble Sort

The below C program sorts the given array into ascending order using bubble sort.

// C program for implementation of Bubble sort
#include <stdio.h>

void swap(int* arr, int i, int j) {
    int temp = arr[i];
    arr[i] = arr[j];
    arr[j] = temp;
}

void bubbleSort(int arr[], int n) {
    for (int i = 0; i < n - 1; i++) {
      
        // Last i elements are already in place, so the loop
        // will only num n - i - 1 times
        for (int j = 0; j < n - i - 1; j++) {
            if (arr[j] > arr[j + 1])
                swap(arr, j, j + 1);
        }
    }
}

int main() {
    int arr[] = { 6, 0, 3, 5 };
    int n = sizeof(arr) / sizeof(arr[0]);

    // Calling bubble sort on array arr
    bubbleSort(arr, n);

    for (int i = 0; i < n; i++)
        printf("%d ", arr[i]);

    return 0;
}

Output
0 3 5 6 

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

Optimization

As we may notice, the above bubble sort algorithm still completed the third pass even when the array was sorted in the second pass. We can optimize it using a new variable swapped 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 Program with Optimized implementation of Bubble sort
#include <stdbool.h>
#include <stdio.h>

void swap(int *a, int *b) {
    int temp = *a;
    *a = *b;
    *b = temp;
}

void bubbleSort(int arr[], int n) {
    for (int i = 0; i < n - 1; i++) {

        // swapped variable to signal if there is a
        // swap happened in the inner loop
        // initially set to false
        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;
    }
}

int main()
{
    int arr[] = {6, 0, 3, 5};
    int n = sizeof(arr) / sizeof(arr[0]);

    // Calling bubble sort on array arr
    bubbleSort(arr, n);
  
    for (int i = 0; i < n; i++)
        printf("%d ", arr[i]);
    return 0;
}

Output
0 3 5 6 

Time Complexity: O(n2)
Auxiliary Space: O(1)

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

Bubble Sort in C – FAQs

Is Bubble Sort stable?

Yes, it maintains the relative order of equal elements.

Is Bubble Sort in-place?

Yes, it does not require any extra memory.

When should I use Bubble Sort?

Use it for small datasets or educational purposes due to its simplicity but avoid it for large datasets because of its inefficiency.



Next Article
Practice Tags :

Similar Reads

three90RightbarBannerImg