Bubble Sort is one of the simplest sorting algorithms in computer science and is often used as a learning tool for beginners. It repeatedly steps through the list to be sorted, compares adjacent elements, and swaps them if they are in the wrong order. This process continues until no more swaps are needed, indicating the list is sorted.

In C programming, bubble sort is a great way to practice key programming concepts like loops, arrays, and conditionals. C is a high-performance language widely used for system and application software, making it ideal for implementing efficient sorting algorithms like bubble sort. When writing a bubble sort program in C, you can see how the language’s structure supports manual memory management and control over hardware, giving you more insight into how sorting works under the hood.

Ready to master the MERN Stack? Join our Full Stack Developer - MERN Stack Master's program and accelerate your career with comprehensive development and testing skills. Contact us today to get started!

What is a Bubble Sort?

Bubble Sort repeatedly compares adjacent elements and swaps them if they are in the wrong order. The algorithm iterates through the list multiple times until no more swaps are needed, resulting in a sorted sequence. During each iteration, the largest unsorted element "bubbles" up to its correct position, hence the name "Bubble Sort."

Watch the video below to learn about the bubble sort algorithm and how it works in real-time.

Unleash Your Career as a Full Stack Developer!

Full Stack Developer - MERN StackEXPLORE COURSE
Unleash Your Career as a Full Stack Developer!

How Does Bubble Sort Work?

Bubble Sort is a simple comparison-based sorting algorithm that works by repeatedly stepping through the list, comparing adjacent elements, and swapping them if they are in the wrong order. This process is repeated until no swaps are needed, so the list is sorted.

How Bubble Sort Works:

  1. Pass-Through the List: In each iteration, the algorithm starts from the beginning of the array and compares each pair of adjacent elements.
  2. Swapping Elements: If the current element exceeds the next element, they are swapped. This way, the largest element in the unsorted portion "bubbles up" to its correct position at the end of the list.
  3. Multiple Iterations: The process is repeated for the remaining unsorted portion of the list. After each iteration, one less element (the last element) must be considered as it's already sorted.
  4. Completion: The algorithm stops when no more swaps are needed during a full pass through the array, meaning the list is sorted.

While Bubble Sort is simple and easy to understand, it is not the most efficient for large datasets, as its time complexity is O(n²) in the worst and average cases. However, it’s often a good starting point for small lists or educational purposes to understand sorting algorithms.

Advance Your MERN Stack Career in 6 Months!

Full Stack Developer - MERN StackEXPLORE COURSE
Advance Your MERN Stack Career in 6 Months!

Bubble Sort Code in Python, Java, and C/C++

Bubble Sort Code in Python

def bubbleSort(array): 
 # loop to access each array element
 for i in range(len(array)):
 # loop to compare array elements
  for j in range(0, len(array) - i - 1):
   # compare two adjacent elements
   # change > to < to sort in descending order
  if array[j] > array[j + 1]:
  # swapping elements if elements
  # are not in the intended order
        temp = array[j] 
        array[j] = array[j+1]
        array[j+1] = temp
data = [-5, 72, 0, 33, -9]
bubbleSort(data)
print('Sorted Array in Ascending Order:') 
print(data)

Bubble Sort Code in Java

import java.util.Arrays;
class Main {
  // perform the bubble sort
  static void bubbleSort(int array[]) {
    int size = array.length;
    // loop to access each array element
    for (int i = 0; i < size - 1; i++)
         // loop to compare array elements
  for (int j = 0; j < size - i - 1; j++)
        // compare two adjacent elements
     // change > to < to sort in descending order
        if (array[j] > array[j + 1]) {
          // swapping occurs if elements
         // are not in the intended order
          int temp = array[j];
          array[j] = array[j + 1];
          array[j + 1] = temp;
        }
  }
 public static void main(String args[]) { 
    int[] data = { -5, 72, 0, 33, -9 };
    // call method using class name   
Main.bubbleSort(data);
   System.out.println("Sorted Array in Ascending Order:");
   System.out.println(Arrays.to String(data)); 
  }
}

Bubble Sort Code in C Programming

// Bubble sort in C
#include <stdio.h>
// perform the bubble sort
void bubbleSort(int array[], int size) {
  // loop to access each array element
  for (int step = 0; step < size - 1; ++step) {  
    // loop to compare array elements
    for (int i = 0; i < size - step - 1; ++i) {
     // compare two adjacent elements
      // change > to < to sort in descending order
      if (array[i] > array[i + 1]) {
        // swapping occurs if elements 
        // are not in the intended order
         int temp = array[i];
        array[i] = array[i + 1]; 
        array[i + 1] = temp;
      }
    } 
  } 
} 
// print array
void printArray(int array[], int size) { 
  for (int i = 0; i < size; ++i) {
    printf("%d  ", array[i]); 
  }
  printf("\n"); 
}
int main() { 
  int data[] = {-5, 72, 0, 33, -9};
  // find the array's length
  int size = sizeof(data) / sizeof(data[0]);
  bubbleSort(data, size);
  printf("Sorted Array in Ascending Order:\n");
  printArray(data, size);
}

Bubble Sort Code in C++

#include <iostream>
using namespace std;
// perform bubble sort
void bubbleSort(int array[], int size) {
  // loop to access each array element
  for (int step = 0; step < size; ++step) {    
  // loop to compare array elements
   for (int i = 0; i < size - step; ++i) {
   // compare two adjacent elements
    // change > to < to sort in descending order     
 if (array[i] > array[i + 1]) {
 // swapping elements if elements
// are not in the intended order
        int temp = array[i];
        array[i] = array[i + 1];
        array[i + 1] = temp;
      }
    }
  }
} 
// print array
void printArray(int array[], int size) {
  for (int i = 0; i < size; ++i) {
    cout << "  " << array[i];
  }
  cout << "\n";
}
int main() {
  int data[] = {-2, 45, 0, 11, -9};
  // find array's length
  int size = sizeof(data) / sizeof(data[0]); 
  bubbleSort(data, size);
   cout << "Sorted Array in Ascending Order:\n";  
  printArray(data, size);
}

Become a Full Stack Developer in Just 6 Months!

Full Stack Developer - MERN StackEXPLORE COURSE
Become a Full Stack Developer in Just 6 Months!

C Program for Bubble Sort Using for Loop

We will write the first C program for bubble sort using a for loop. In this example, we will use a nested for loop in C to sort the elements of a one-dimensional array. To begin with, we will ask for the total number of elements and then the values from the user. Once we get the elements, we will use the for loop to iterate through them and sort them in ascending order.

#include <stdio.h>
int main(){
    int arr[50], num, x, y, temp;    
    printf("Please Enter the Number of Elements you want in the array: ");
    scanf("%d", &num);    
    printf("Please Enter the Value of Elements: ");
    for(x = 0; x < num; x++)
        scanf("%d", &arr[x]);
    for(x = 0; x < num - 1; x++){       
        for(y = 0; y < num - x - 1; y++){          
            if(arr[y] > arr[y + 1]){               
                temp = arr[y];
                arr[y] = arr[y + 1];
                arr[y + 1] = temp;
            }
        }
    }
    printf("Array after implementing bubble sort: ");
    for(x = 0; x < num; x++){
        printf("%d  ", arr[x]);
    }
    return 0;
}

Output:

C_Program_for_Bubble_Sort_1

C Program for Bubble Sort Using While Loop

We will follow the same method as in the previous example for this example. The only difference is that we will replace the for loop with the nested while loop.

#include <stdio.h>
int main(){
    int arr[50], num, x, y, temp;  
    printf("Please Enter the Number of Elements you want in the array: ");
    scanf("%d", &num);   
    printf("Please Enter the Value of Elements: ");
    for(x = 0; x < num; x++)
        scanf("%d", &arr[x]);
    x = 0;
    while(x < num - 1){
        y = 0;        
        while(y < num - x - 1){
            if(arr[y] > arr[y + 1]){
                temp = arr[y];
                arr[y] = arr[y + 1];
                arr[y + 1] = temp;
            }
            y++;
        }       
        x++;
    }   
    printf("Array after implementing bubble sort: ");
    for(x = 0; x < num; x++)
        printf("%d  ", arr[x]);
    return 0;
}

Output:

C_Program_for_Bubble_Sort_2.

C Program for Bubble Sort Using Functions

In this C program for bubble sorting, we will create a user-defined function and write down the mechanism of sorting the array elements inside it. Here’s how to implement bubble sort in C using functions.

#include <stdio.h>
void bubbleSortExample(int arr[], int num){
    int x, y, temp;   
    for(x = 0; x < num - 1; x++){
        for(y = 0; y < num - x - 1; y++){    
            if(arr[y] > arr[y + 1]){
                temp = arr[y];
                arr[y] = arr[y + 1];
                arr[y + 1] = temp;
            }
        }
    }
}
int main(){
    int arr[50], n, x;  
    printf("Please Enter the Number of Elements you want in the array: ");
    scanf("%d", &n);    
    printf("Please Enter the Value of Elements: ");
    for(x = 0; x < n; x++)
        scanf("%d", &arr[x]);    
    bubbleSortExample(arr, n);
    printf("Array after implementing bubble sort: ");    
    for(x = 0; x < n; x++){
        printf("%d  ", arr[x]);
    }   
    return 0;
}

Output:

C_Program_for_Bubble_Sort_3

C Program for Bubble Sort Using Pointers

In this C program for bubble sorting, we have used C pointers. All we did was create another user-defined function to standardize pointers. Here’s how the implementation goes.

#include <stdio.h>
void SwapFunc(int *i, int *j){
    int Temp;
    Temp = *i;
    *i = *j;
    *j = Temp;
}
void bubbleSortExample(int arr[], int num){
    int x, y, temp;   
    for(x = 0; x < num - 1; x++) {    
        for(y = 0; y < num - x - 1; y++) {    
            if(arr[y] > arr[y + 1]) {
                SwapFunc(&arr[y], &arr[y + 1]);
            }
        }
    }
}
int main(){
    int arr[50], n, x;   
    printf("Please Enter the Number of Elements you want in the array: ");
    scanf("%d", &n);    
    printf("Please Enter the Value of Elements: ");
    for(x = 0; x < n; x++)
        scanf("%d", &arr[x]);    
    bubbleSortExample(arr, n);
    printf("Array after implementing bubble sort: ");
    for(x = 0; x < n; x++)
    {
        printf("%d  ", arr[x]);
    }
    return 0;
}

Output:

C_Program_for_Bubble_Sort_4.

Boost your career with our Full Stack Developer - MERN Stack Master's program! Gain in-depth expertise in development and testing with the latest technologies. Enroll today and become a skilled MERN Stack Developer!

C Program for Optimized Implementation of Bubble Sort

All the elements are compared in standard bubble sorting, even if the last elements are already sorted based on the previous iterations. This increases the execution time, which can be reduced by optimizing the C program for bubble sort. All we need to do is introduce an additional variable; let’s name it Swap.

The variable Swap is set as true if the swapping of elements has occurred; otherwise, it is false. When the program finds that the value of the Swap variable is false, it will understand that the sorting is already done and break out of the loop. This will reduce the execution time by optimizing the algorithm. The code below shows how to optimize the C program for bubble sort.

#include <stdio.h>
// Function for bubble sorting
void bubbleSortExample(int arr[], int n){
    for (int i = 0; i < n - 1; ++i){   
        int Swap = 0;    
        // Comparing array elements
        for (int x = 0; x < n - i - 1; ++x){    
            if (arr[x] > arr[x + 1]){
                int temp = arr[x];
                arr[x] = arr[x + 1];
                arr[x + 1] = temp;      
                Swap = 1;
            }
        }    
        if (Swap == 0){ // No swapping required
            break;
        }    
    }
}
void displayArray(int arr[], int n){    
    for (int x = 0; x < n; ++x){
        printf("%d  ", arr[x]);
    }    
    printf("\n");
}
// Driver method
int main(){
    int data[] = {27, 13, -54, 93, -20};  
  // finding array's length
  int n = sizeof(data) / sizeof(data[0]);
  bubbleSortExample(data, n);  
  printf("Array after implementing bubble sort: \n");
  displayArray(data, n); 
}

Output:

C_Program_for_Bubble_Sort_5.

Complexity Analysis Bubble Sort

Time Complexity Analysis of Bubble Sort

Bubble Sort is a simple sorting algorithm that repeatedly steps through the list to be sorted, compares adjacent elements, and swaps them if they are in the wrong order. The process is repeated until the list is sorted.

1. Best Case

  • Time Complexity: \(O(n)\)  
  • Description: This occurs when the array is already sorted. The algorithm only makes one pass through the array, performing comparisons but no swaps. 

2. Average Case

  • Time Complexity: \(O(n^2)\)  
  • Description: In the average scenario, the algorithm has to perform several passes through the list, making comparisons and swaps. This quadratic time complexity arises because, in the worst-case scenario, every element may have to be compared with every other element.

3. Worst Case

  • Time Complexity: \(O(n^2)\)  
  • Description: This occurs when the array is sorted in reverse order. In this situation, every possible pair of elements has to be compared and swapped, leading to the maximum number of iterations.

Space Complexity Analysis of Bubble Sort

Space Complexity measures the amount of memory space the algorithm requires to run as a function of the input size.

1. Auxiliary Space

  • Space Complexity: \(O(1)\)  
  • Description: Bubble sort is an in-place sorting algorithm. It requires constant additional space for the temporary variable used during swapping, regardless of the input array size. Hence, the space complexity is constant.
Also Read: Time and Space Complexity

Advantages and Disadvantages of Bubble Sort

Advantages of Bubble Sort

  • Simplicity: Easy to understand and implement.
  • Minimal code: Requires minimal lines of code for implementation.
  • Suitable for small datasets: Works well for small-sized arrays or lists.
  • Stable: Elements with equal values retain their relative order.

Disadvantages of Bubble Sort

  • Inefficiency: The time complexity of O(n^2) makes it inefficient for large datasets.
  • Slow for large arrays: It takes more time to sort than more efficient algorithms.
  • Not suitable for real-world applications: Other sorting algorithms like Quick Sort or Merge Sort are preferred for practical use.
  • Lacks scalability: Does not perform well when dealing with many elements.

Boost Your Coding Skills. Nail Your Next Interview

Full Stack Developer - MERN StackExplore Program
Boost Your Coding Skills. Nail Your Next Interview

Wrapping It Up

In this article, you have learned what bubble sorting is and how you can write a C program for bubble sorting in different ways. You can now put your knowledge to practice and hone your skills. You can sign up for our SkillUp platform to learn about more fundamental C programming concepts. The platform offers numerous free courses to help you learn and understand concepts of various programming languages, including C and C++.

Learning the fundamentals of a single programming language is not enough in today’s competitive world. Hence, it is vital to master multiple languages. You can opt for our Full Stack Developer - MERN Stack for that. The certification course is a mixture of some of the most popular development languages in the world. Registering for the course lets you learn about multiple programming languages and relevant tools to land a lucrative, high-paying job in a multinational company.

FAQs

1. What is the Boundary Case for Bubble Sort?

The boundary case for bubble sort typically refers to the scenario where the input array has a size of 0 or 1. In these cases, the array is considered sorted, and bubble sort will not perform any operations, leading to constant time complexity O(1)O(1)O(1).

2. Does sorting happen in place in Bubble Sort?

Yes, bubble sort is an in-place sorting algorithm. It sorts the elements within the original array without needing additional data structures, using only a small, constant amount of extra space for temporary variable storage during swaps.

3. Is the Bubble Sort algorithm stable?

Yes, bubble sort is a stable sorting algorithm. It preserves the relative order of equal elements by only swapping adjacent elements when necessary, ensuring that duplicate values maintain their original sequence in the sorted output.

4. What is an example of Bubble Sort?

An example of bubble sort: Given the array [5, 1, 4, 2, 8], bubble sort compares and swaps adjacent elements. After the first pass, the array becomes [1, 4, 2, 5, 8]. Repeating this process sorts the array into [1, 2, 4, 5, 8].

5. Which sorting is best in C?

The best sorting algorithm in C depends on the context. Quick sort is generally preferred for its efficiency on average cases with O(nlog⁡n)O(n \log n)O(nlogn) time complexity. However, insertion sort can be effective for small datasets, and for stable sorting, merge sort is a strong choice.

Our Software Development Courses Duration And Fees

Software Development Course typically range from a few weeks to several months, with fees varying based on program and institution.

Program NameDurationFees
Caltech Coding Bootcamp

Cohort Starts: 24 Feb, 2025

6 Months$ 8,000
Automation Test Engineer Masters Program

Cohort Starts: 8 Jan, 2025

8 months$ 1,499
Full Stack Java Developer Masters Program

Cohort Starts: 8 Jan, 2025

7 months$ 1,449
Full Stack (MERN Stack) Developer Masters Program

Cohort Starts: 8 Jan, 2025

6 Months$ 1,449