C Program for Bubble Sort to Sort Elements in an Order

There might come situations when you would want to order data in a specific order. That’s when a sorting algorithm will come in handy. Bubble sort in C is a straightforward sorting algorithm that checks and swaps elements if they are not in the intended order. It compares two adjacent elements to find which one is greater or lesser and switches them based on the given condition until the final place of the element is found. In this article, you will learn about bubble sort and how to write a C program for bubble sort implementation using different ways.

The Bubble Sort Algorithm in C

The basic bubble sort algorithm can be explained as follows:

bubbleSort(array)

  for i <- 1 to indexOfLastUnsortedElement-1

    if leftElement > rightElement

      swap leftElement and rightElement

end bubbleSort

This algorithm does the swapping of elements to get the final output in the desired order. For instance, if you pass an array consisting of the elements: (6, 3, 8, 2, 5, 7), the final array after the bubble sort implementation will be: (2, 3, 5, 6, 7, 8).

Working of Bubble Sort in C

As mentioned, the C program for bubble sort works by comparing and swapping adjacent elements in an array. Let’s understand this in a step-by-step method:

Suppose we want to sort an array, let’s name it arr, with n elements in ascending order; this is how the bubble sort algorithm will work.

  1. Starts from the first index: arr[0] and compares the first and second element: arr[0] and arr[1]
  2. If arr[0] is greater than arr[1], they are swapped
  3. Similarly, if arr[1] is greater than arr[2], they are swapped
  4. The above process continues until the last element arr[n-1]

All four steps are repeated for each iteration. Upon completing each iteration, the largest unsorted element is moved to the end of the array. Finally, the program ends when no elements require swapping, giving us the array in ascending order. Now that we know the working of the bubble sort let’s implement it in C programming using different methods.

Stand Out From Your Peers this Appraisal Season

Start Learning With Our FREE CoursesEnroll Now
Stand Out From Your Peers this Appraisal Season

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 a use 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 the elements 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

For this example, we will follow the same method as in the previous 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 sort, 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 sort, we have used C pointers. All we did was create another user-defined function to standardize the use of pointers in it. 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.

Full Stack Web Developer Course

To become an expert in MEAN StackView Course
Full Stack Web Developer Course

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.

The Complexity of Bubble Sort in C

Time Complexity

  • Worst Case Complexity: If the array elements are in descending order and we want to make it in ascending order, it is the worst case. The time complexity for the worst case is O(n²).
  • Best Case Complexity: The best case is when all the elements are already sorted, and no swapping is required. The time complexity in this scenario is O(n).
  • Average Case Complexity: This is the case when the elements are jumbled. The time complexity for the average case in bubble sort is O(n²).

Space Complexity

  • Space complexity for the standard bubble sort algorithm is O(1) as there is one additional variable required to hold the swapped elements temporarily.
  • Space complexity for optimized implementation of the bubble sort algorithm is O(2). This is because two additional variables are required.

Applications of Bubble Sort in C

The best scenarios to use the bubble sort program in C is when:

  • Complexity does not matter
  • Slow execution speed does not matter
  • Short and easy to understand coding is preferred

Alternatives to Bubble Sort in C

Besides the bubble sort algorithm, you can also sort arrays and lists using the following sorting algorithms.

  • Quicksort
  • Selection sort
  • Merge sort
  • Insertion sort
Advance your career as a MEAN stack developer with the Full Stack Web Developer - MEAN Stack Master's Program. Enroll now!

Wrapping It Up

In this article, you have learned what bubble sorting is and how you can write a C program for bubble sort in different ways. You can now put your knowledge to practice and hone your skills. To learn about more such fundamental C programming concepts, you can sign up for our SkillUp platform. 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 Web Development Certification Course for that. The certification course is a mixture of some of the most popular development languages in the world. By registering for the course, you get the chance to learn about multiple programming languages and relevant tools to land yourself a lucrative high-paying job in a multinational company.

About the Author

SimplilearnSimplilearn

Simplilearn is one of the world’s leading providers of online training for Digital Marketing, Cloud Computing, Project Management, Data Science, IT, Software Development, and many other emerging technologies.

View More
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.