C Program to Implement Bubble Sort

What is Bubble Sort?

Bubble Sort in C is a simple sorting algorithm that works by repeatedly stepping through the list to be sorted, comparing each pair of adjacent items, and swapping them if they are in the wrong order. Bubble sort technique is used to sort an array of values in increasing or decreasing order.

Problem Description

Write a C program to perform the bubble sort.

Expected Input and Output

1. Average case (Unsorted array): When the input array has random distribution of numbers.

For example:

If the input array is {4, 6, 1, 2, 5, 3}      
the expected output array will have data as {1, 2, 3, 4, 5, 6}

2. Best case (Sorted Array): When the input array is already sorted, in that case we have to make minimum number of swaps.

For example:

advertisement
advertisement
If the input array has data as {-3, 31, 66}        
then the expected output array will have data as {-3, 31, 66}

3. Worst Case (Reverse sorted array): When the array is sorted in reverse manner, in that case we have to make maximum number of swaps.

For example:

If the input array has elements as {9, 8, 6, 3, 1}
then the output array will have data as {1, 3, 6, 8, 9}
Bubble Sort Algorithm

1. In Bubble sort algorithm we compare the first two elements of an array and swap them if required.
2. If we want to sort the elements of array in ascending order and if the first element is greater than second then, we need to swap the elements.
3. If the first element is smaller than second, we don’t need to swap the elements. This process go on until last and second last element is compared and swapped.

Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!
Pseudocode for Bubble Sort
bubble_sort(array):
  for i in range(len(array) - 1):
    for j in range(len(array) - i - 1):
      if array[j] > array[j + 1]:
        array[j], array[j + 1] = array[j + 1], array[j]

Bubble Sort Example:

If we have the array as {40,10,50,70,30}
and we apply bubble sort to sort the array,
then the resultant array after each iteration will be as follows:

               Original array: {40, 10, 50, 70, 30}

Array after first iteration          10  ->   40   ->   50   ->   30   ->   70
Array after second iteration         10  ->   40   ->   30   ->   50   ->   70
Array after third iteration          10  ->   30   ->   40   ->   50   ->   70
Array after fourth iteration         10  ->   30   ->   40   ->   50   ->   70
            
               Sorted array is  10  30  40  50  70
Problem Solution

There are many approaches to implement the bubble sort algorithm. Let’s take a detailed look at all the approaches to perform bubble sort in C.

advertisement
Method 1: Bubble Sort Program in C (Iterative Approach)

In the iterative approach to sort the array, we have to follow the given steps:

  1. Take an element from the beginning of the array.
  2. Compare it with its next element from the start to the end of the unsorted array.
  3. If the first element is greater than the second element then swap them.
  4. Repeat the above steps until the array does not sort.
Program/Source Code

Here is the source code of the C program to sort integers using Bubble Sort technique. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C Program to sort an array using Bubble Sort technique
  3.  */
  4.  
  5. #include <stdio.h>
  6. void bubblesort(int arr[], int size)
  7. {
  8.     int i, j;
  9.     for (i = 0;  i < size; i++)
  10.     {
  11.         for (j = 0; j < size - i; j++)
  12.         {
  13.             if (arr[j] > arr[j+1])
  14.                 swap(&arr[j], &arr[j+1]);
  15.  
  16.         }
  17.     }
  18. }
  19. void swap(int *a, int *b)
  20. {
  21.     int temp;
  22.     temp = *a;
  23.     *a = *b;
  24.     *b = temp;
  25. }
  26. int main()
  27. {
  28.     int array[100], i, size;
  29.     printf("How many numbers you want to sort:  ");
  30.     scanf("%d", &size);
  31.     printf("\nEnter %d numbers : ", size);
  32.     for (i = 0; i < size; i++)
  33.         scanf("%d", &array[i]);
  34.     bubblesort(array, size);
  35.     printf("\nSorted array is ");
  36.  
  37.     for (i = 0; i < size; i++)
  38.         printf(" %d ", array[i]);
  39.     return 0;
  40. }

Time Complexity: O(n2)
In the worst case, it should have to swap the n elements if the array is reverse sorted. The size of the list is n.

Space Complexity: O(1)
There is no need to use an extra space that depends on the size of the array. Hence the space completixty of bubble sort program is constant.

advertisement
Runtime Test Cases

In this case, we are entering the numbers “345, 3, 20 35, 333” as input to sort them using bubble sort in ascending order.

$ gcc bubblesort.c -o bubblesort
$ ./bubblesort
 
How many numbers you want to sort: 5
 
Enter 5 numbers : 345 3 20 35 333
 
Sorted array is : 3 20 35 333 345

Method 2: (Recursive Bubble Sort)

To sort the array using the recursive approach we have to follow the given steps:

  1. If the array length is less than 1 then stop the recursion.
  2. On every traversing, place the largest element at the end of the array.
  3. Repeat the above steps until the array does not sort.
Program/Source Code

Here is the source code of the C program to sort integers using Bubble Sort technique. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * Bubble Sort Program in C using recursion
  3.  */
  4.  
  5. #include <stdio.h>
  6.  
  7. // function prototyping 
  8. void bubble_sort(int*, int);
  9. void print(int*, int);
  10.  
  11. int main()
  12. {
  13.     // initialize the integer array
  14.     int arr[8] = {23, 3, 56, 78, 12, 1, 45, 21};
  15.  
  16.     // size of the array
  17.     int size = sizeof(arr) / sizeof(arr[0]);
  18.  
  19.     // calling the function bubble sort
  20.  
  21.     printf("\nArray before sorting: \n");
  22.     print(arr, size);
  23.  
  24.     bubble_sort(arr, size);
  25.     printf("\n\nArray after sorting: \n");
  26.     print(arr, size);
  27.     return 0;
  28. }
  29.  
  30. /* bubble_sort method takes the array and its size as parameter */
  31. void bubble_sort(int arr[], int size)
  32. {
  33.     // base condition, when the array size is 1
  34.     if(size <= 0)
  35.     {
  36.         return;
  37.     }
  38.  
  39.     // place the largest element at the end of the unsorted size of the array
  40.     for(int j=0; j<size-1; j++)
  41.     {
  42.         if(arr[j] > arr[j+1])
  43.         {
  44.             int temp = arr[j];
  45.             arr[j] = arr[j+1];
  46.             arr[j+1] = temp;
  47.         }
  48.     }
  49.  
  50.     // decrement the size of the array
  51.     size -= 1;
  52.  
  53.     // recursive call to the bubble sort function
  54.     bubble_sort(arr, size);
  55.  
  56. }
  57.  
  58. /* function to print the array of given size */
  59. void print(int arr[], int size)
  60. {
  61.     for(int i=0; i<size; i++)
  62.     {
  63.         printf("%d ", arr[i]);
  64.     }
  65. }
Program Explanation

In the recursive approach, we have to call the function bubble sort until the array does not sort. In every function call, we have to place the largest element from the array at the unsorted array.

Time Complexity: O(n2)
Time taken to sort the array using bubble sort in the recursive approach is quadratic since we are placing the largest element on every iteration of the n-size array.

Space Complexity: O(n)
There are n functions calling stacks required to sort the array, where n is the size of the array.

Runtime Test Cases

In this case, we are entering the numbers “23 3 56 78 12 1 45 21” as input to sort them using bubble sort in ascending order.

Array before sorting: 
23 3 56 78 12 1 45 21 
 
Array after sorting: 
1 3 12 21 23 45 56 78

Method 3: Sort N Numbers in Ascending Order using Bubble Sort

In this method we sort the numbers in ascending order using bubble sort.

Program/Source Code

Here is source code of the C program to sort the numbers in ascending order using bubble sort. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C program to sort N numbers in ascending order using Bubble sort
  3.  * and print both the given and the sorted array
  4.  */
  5. #include <stdio.h>
  6. #define MAXSIZE 10
  7.  
  8. void main()
  9. {
  10.     int array[MAXSIZE];
  11.     int i, j, num, temp;
  12.  
  13.     printf("Enter the value of num \n");
  14.     scanf("%d", &num);
  15.     printf("Enter the elements one by one \n");
  16.     for (i = 0; i < num; i++)
  17.     {
  18.         scanf("%d", &array[i]);
  19.     }
  20.     printf("Input array is \n");
  21.     for (i = 0; i < num; i++)
  22.     {
  23.         printf("%d\n", array[i]);
  24.     }
  25.     /*   Bubble sorting begins */
  26.     for (i = 0; i < num; i++)
  27.     {
  28.         for (j = 0; j < (num - i - 1); j++)
  29.         {
  30.             if (array[j] > array[j + 1])
  31.             {
  32.                 temp = array[j];
  33.                 array[j] = array[j + 1];
  34.                 array[j + 1] = temp;
  35.             }
  36.         }
  37.     }
  38.     printf("Sorted array is...\n");
  39.     for (i = 0; i < num; i++)
  40.     {
  41.         printf("%d\n", array[i]);
  42.     }
  43. }
Runtime Test Cases

In this case, we are entering the numbers “23, 45, 67, 89, 12 and 34” as input to sort them using bubble sort in ascending order.

Enter the value of num
6
Enter the elements one by one
23
45
67
89
12
34
Input array is
23
45
67
89
12
34
Sorted array is...
12
23
34
45
67
89

To practice programs on every topic in C, please visit “Programming Examples in C”, “Data Structures in C” and “Algorithms in C”.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.