1. Home

Explore C Tutorials: From Beginner Concepts to Advanced Techniques

Dive into our C tutorials and expand your programming skills. From fundamental concepts to advanced techniques, we've got you covered. Start your journey to C mastery today

• 130 Lessons
• 22 Hours
20.Â

C Program for Bubble Sort

Updated on 19/07/20243,604 Views

Introduction

Bubble Sort is a straightforward sorting algorithm that operates by repetitively stepping through a list, comparing all pairs of adjacent items and swapping them if they follow an incorrect order. The pass through the list is repeated until no more swaps are needed, indicating that the list is sorted.

The Bubble Sort in C Programming?

The Bubble Sort algorithm can be implemented in C programming in multiple ways, but the basic concept remains the same. Elements of the list are compared with each other in pairs, starting from the beginning of the list. If the first element of the pair is greater than the second, the positions of the elements are swapped. This process is repeated until the entire list is sorted.

How Does Bubble Sort Work?

Bubble sort works by making multiple passes over a list, comparing and swapping elements, and then repeating the process until the list is sorted.

Let's take an example: Suppose we have the list [5, 3, 8, 4, 2].

1. In the first pass, Bubble sort starts at the first pair of elements, 5 and 3. It compares the two numbers; since 5 is greater than 3, it swaps them. The list looks like [3, 5, 8, 4, 2].
2. Next, it compares 5 and 8; since 5 is not greater than 8, it doesn't swap them.
3. Then it compares 8 and 4 and swaps them because 8 is greater than 4. The list looks like [3, 5, 4, 8, 2].
4. It repeats the same process for 8 and 2, resulting in [3, 5, 4, 2, 8].
5. After the first pass, we can see that the largest number, 8, has moved to the correct position at the end of the list.
6. The process repeats for the remaining elements until the entire list is sorted.

How Does the C Program for Bubble Sort Work?

The Bubble Sort algorithm can be implemented in C programming using loops such as for and while, functions, or pointers. The algorithm remains the same; only the implementation varies.

In C, we use a nested loop where the outer loop runs from the beginning of the array to the end, and the inner loop runs from the beginning of the array to the last unsorted element. They are swapped; if the current element in the inner loop is greater than the next element.

 `for(int l = 0; x < n-1; m++) { Â  Â  Â  Â  for(int m = 0; m < n-i-1; m++) {Â  Â  Â  Â  if(array[m] > array[m+1]) {Â  Â  Â  Â  Â  Â  // Swap array[m] and array[m+1]Â  Â  Â  Â  Â  Â  int temp = array[m];Â  Â  Â  Â  Â  Â  array[m] = array[m+1];Â  Â  Â  Â  Â  Â  array[m+1] = temp;Â  Â  Â  Â  }Â  Â  }}`

Here, n is the number of elements in the array arr[]. This code will sort the array in ascending order.

C Program for Bubble Sort Using for Loop

Here's a full implementation of Bubble Sort using a for loop in C:

 `#include voidÂ bubbleSort(intÂ array[],Â intÂ n) {Â  Â  for(int l = 0; l < n-1; l++) {Â  Â  Â  Â  for(int m = 0; m < n-1; m++) {Â  Â  Â  Â  Â  Â  if(array[m] > array[m+1]) {Â  Â  Â  Â  Â  Â  Â  Â  // Swap array[m] and array[jm+1]Â  Â  Â  Â  Â  Â  Â  Â  int temp = array[m];Â  Â  Â  Â  Â  Â  Â  Â  array[m] = array[m+1];Â  Â  Â  Â  Â  Â  Â  Â  array[m+1] = temp;Â  Â  Â  Â  Â  Â  }Â  Â  Â  Â  }Â  Â  }}voidÂ printArray(intÂ array[],Â intÂ size) {Â  Â  for (int l = 0; l < size; l++)Â  Â  Â  Â  printf("%d ", array[l]);Â  Â  printf("\n");}intÂ main() {Â  Â  int array[] = {46, 34, 25, 23, 22, 11, 90};Â  Â  int n = sizeof(array) / sizeof(array[0]);Â  Â  bubbleSort(array, n);Â  Â  printf("Sorted array: \n");Â  Â  printArray(array, n);Â  Â  return 0;}`

In this program, we define the bubbleSort() function, which performs the sorting operation. Inside the bubbleSort() function, we use a nested for loop to repeatedly iterate over the array, comparing and swapping elements as necessary.

The printArray() function prints the elements of the array. It's used to display the array before and after sorting.

The main() function is where our program begins execution. The array arr[] to be sorted is defined here, and the bubbleSort() function is called to sort this array. The sorted array is then printed on the screen.

C Program for Bubble Sort Using While Loop

Using a while loop, we can also implement the Bubble Sort algorithm. Here is a simple program for that:

 `#include voidÂ bubbleSort(intÂ array[],Â intÂ n)Â {Â  Â  int l = n-1;Â  Â  while(l > 0) {Â  Â  Â  Â  int m = 0;Â  Â  Â  Â  while(m < l) {Â  Â  Â  Â  Â  Â  if(array[m] > array[m+1]) {Â  Â  Â  Â  Â  Â  Â  Â  // Swap array[m] and array[m+1]Â  Â  Â  Â  Â  Â  Â  Â  int temp = array[m];Â  Â  Â  Â  Â  Â  Â  Â  array[m] = array[m+1];Â  Â  Â  Â  Â  Â  Â  Â  array[m+1] = temp;Â  Â  Â  Â  Â  Â  }Â  Â  Â  Â  Â  Â  m++;Â  Â  Â  Â  }Â  Â  Â  Â  l--;Â  Â  }}voidÂ printArray(intÂ array[],Â intÂ size)Â {Â  Â  for (int l = 0; l < size; l++)Â  Â  Â  Â  printf("%d ", array[l]);Â  Â  printf("\n");}intÂ main()Â {Â  Â  int array[] = {49, 34, 55, 12, 22, 61, 90};Â  Â  int n = sizeof(array) / sizeof(array[0]);Â  Â  bubbleSort(array, n);Â  Â  printf("Sorted array: \n");Â  Â  printArray(array, n);Â  Â  return 0;}`

This program works similarly to the previous one, with the difference being that we are using a while loop to control the flow of our program instead of a for loop.

C Program for Bubble Sort Using Functions

Functions allow us to modularise our code. Here is a bubble sort program in C using function.

 `#include voidÂ swap(intÂ *xp,Â intÂ *yp)Â {Â  Â  int temp = *xp;Â  Â  *xp = *yp;Â  Â  *yp = temp;}voidÂ bubbleSort(intÂ arr[],Â intÂ n)Â {Â  Â for(int i = 0; i < n-1; i++) { Â  Â  Â  Â  Â  Â for(int j = 0; j < n-i-1; j++) {Â  Â  Â  Â  Â  Â if(arr[j] > arr[j+1]) {Â  Â  Â  Â  Â  Â  Â  Â swap(&arr[j], &arr[j+1]);Â  Â  Â  Â  Â  Â }Â  Â  Â  Â }Â  Â }}voidÂ printArray(intÂ arr[],Â intÂ size)Â {Â  Â  int i;Â  Â  for (i = 0; i < size; i++)Â  Â  Â  Â  printf("%d ", arr[i]);Â  Â  printf("\n");}intÂ main()Â {Â  Â  int arr[] = {64, 34, 25, 12, 22, 11, 90};Â  Â  int n = sizeof(arr)/sizeof(arr[0]);Â  Â  bubbleSort(arr, n);Â  Â  printf("Sorted array: \n");Â  Â  printArray(arr, n);Â  Â  return 0;}`

Here, we've defined a function swap() that takes two pointers and swaps the values they point to. This function is used in the bubbleSort() function to swap the elements of the array if they are in the wrong order.

C Program for Bubble Sort Using Pointers

We can also implement Bubble Sort using pointers. Here's an example of how we can do that:

 `#include voidÂ swap(intÂ *ip,Â intÂ *jp)Â {Â  Â  int temp = *ip;Â  Â  *ip = *jp;Â  Â  *jp = temp;}voidÂ bubbleSort(intÂ *array,Â intÂ n)Â {Â  Â for(int l = 0; l < n-1; l++) { Â  Â  Â  Â  Â  Â for(int m = 0; m < n-l-1; m++) {Â  Â  Â  Â  Â  Â if(*(array+m) > *(array+m+1)) {Â  Â  Â  Â  Â  Â  Â  Â swap((array+m), (array+m+1));Â  Â  Â  Â  Â  Â }Â  Â  Â  Â }Â  Â }}voidÂ printArray(intÂ *array,Â intÂ size)Â {Â  Â  for (int l = 0; l < size; l++)Â  Â  Â  Â  printf("%d ", *(array + l));Â  Â  printf("\n");}intÂ main()Â {Â  Â  int array[] = {64, 47, 25, 28, 22, 17, 90};Â  Â  int n = sizeof(array)/sizeof(array[0]);Â  Â  bubbleSort(array, n);Â  Â  printf("Sorted array: \n");Â  Â  printArray(array, n);Â  Â  return 0;}`

In this code, we use pointers to access the array elements. In the bubbleSort() and printArray() functions, the array argument is replaced by a pointer to the first element of the array. We then use pointer arithmetic to access the elements of the array.

C Program for Optimized Implementation of Bubble Sort

In the standard implementation of Bubble Sort, the algorithm doesn't stop even if the array is sorted before all the iterations are completed. This can lead to unnecessary operations. An optimised version of Bubble Sort introduces a flag to check whether any swapping occurred in the previous pass. If no swaps occur, the array is already sorted, and the algorithm can terminate early. Here's how it's implemented:

 `#include #include voidÂ swap(intÂ *ip,Â intÂ *jp)Â {Â  Â  int temp = *ip;Â  Â  *ip = *jp;Â  Â  *jp = temp;}voidÂ bubbleSort(intÂ array[],Â intÂ n)Â {Â  Â int l, m;Â  Â bool swapped;Â  Â for(l = 0; l < n-1; l++) {Â  Â  Â  Â swapped = false;Â  Â  Â  Â for(m = 0; m < n-l-1; m++) {Â  Â  Â  Â  Â  Â if(array[m] > array[m+1]) {Â  Â  Â  Â  Â  Â  Â  Â swap(&array[m], &array[m+1]);Â  Â  Â  Â  Â  Â  Â  Â swapped = true;Â  Â  Â  Â  Â  Â }Â  Â  Â  Â }Â  Â  Â  Â // If no two elements were swapped by inner loop, then breakÂ  Â  Â  Â if(swapped == false) {Â  Â  Â  Â  Â  Â break;Â  Â  Â  Â }Â  Â }}voidÂ printArray(intÂ array[],Â intÂ size)Â {Â  Â  int l;Â  Â  for(l = 0; l < size; l++)Â  Â  Â  Â  printf("%d ", array[l]);Â  Â  printf("\n");}intÂ main()Â {Â  Â  int array[] = {48, 34, 57, 28, 21, 31, 90};Â  Â  int n = sizeof(array) / sizeof(array[0]);Â  Â  bubbleSort(array, n);Â  Â  printf("Sorted array: \n");Â  Â  printArray(array, n);Â  Â  return 0;}`

In this optimised version, we introduce a boolean variable swapped to check if any swap happened in the current iteration. If no swap occurs in the inner loop, the swapped flag remains false, which indicates that the array is already sorted and breaks the outer loop early, thereby optimising the algorithm.

Optimized Bubble Sort Algorithm

The standard Bubble Sort algorithm can be optimised by introducing a flag that checks if any swap has happened in the last pass. If the flag is false after a pass, it implies the array is sorted, and there is no need for further passes.

Hereâ€™s a proper pseudocode that you can look at to understand how optimized bubble sort algorithm should work:

1. bubbleSort(array[], n)
2. for l from 0 to n-1 do:
3. swapped = false
4. for m from 0 to n-l-1 do:
5. if array[m] > array[m+1] then:
6. swap array[m] and array[m+1]
7. swapped = true
8. if not swapped then:
9. break

The Complexity of Bubble Sort in C

The Bubble Sort algorithm, despite its simplicity, isn't the most efficient for large datasets. Here's why:

• Worst-case time complexity: O(n^2)
• Average-case time complexity: O(n^2)
• Best-case time complexity: O(n)
• Space complexity: O(1)

The Bubble sort time complexity in the best-case scenario, where the input is already sorted, is O(n) because Bubble Sort only makes one pass over the data in this case. But in the average and worst-case scenarios, Bubble Sort must make multiple passes over the data, leading to a time complexity of O(n^2). The space complexity is O(1) because Bubble Sort is an in-place sorting algorithm.

Applications of Bubble Sort in C

Despite being inefficient for larger datasets, Bubble Sort is straightforward to understand and easy to implement, making it suitable for:

• Educational purposes: Due to its simplicity, it's often used in education for teaching sorting algorithms.
• Small datasets: For small arrays or lists, Bubble Sort can be more efficient and faster compared to more complex algorithms.
• Nearly sorted data: If you have a list that's already mostly sorted with just a few elements out of place, Bubble Sort can be very efficient.

Alternatives to Bubble Sort in C

While Bubble Sort is simple and easy to implement, its inefficiency for larger data sets can be a disadvantage. In such cases, other sorting algorithms might be more suitable:

1. Selection Sort in C: Selection Sort segments the input into a sorted and an unsorted region. It repetitively chooses the largest or smallest (based on the ordering) element from the unsorted region and moves it to the sorted region.
2. Insertion Sort in C: Insertion Sort is another simple and intuitive sorting algorithm, it builds the final sorted array one item at a time. It is significantly less effective on expansive lists when compared to more advanced algorithms like heap sort, merge sort or quick sort.

Worst Case Analysis for Bubble Sort

The worst-case scenario for Bubble Sort occurs when the array is sorted in reverse order. In such a case, Bubble Sort would need to make n*(n-1)/2 comparisons and swaps, where n is the number of elements in the array. This leads to a worst-case time complexity of O(n^2). The space complexity remains O(1) as only a single extra space is required for the temporary variable used in swapping.

Conclusion

Bubble Sort is a straightforward sorting algorithm that may not be efficient for large datasets due to its time complexity. However, it has merits in certain situations. Its simplicity, in-place sorting, and stability make it useful for nearly sorted lists or smaller datasets.

If you're interested in algorithms like Bubble Sort and want to further explore computer science and programming, consider checking out upGrad's comprehensive Executive PG Program in Software Development from IIIT-B. The program offers an immersive learning experience, helping development aspirants to gain can hands-on experience to boost their careers.

FAQs

1. How does bubble sort work?

Bubble sort works by consistently swapping the adjacent elements if they are following an incorrect order. The algorithm continues to iterate through the list until it can traverse the entire list without swapping any elements.

2. Is bubble sort efficient?

Bubble sort is simple and suitable for small datasets or nearly sorted lists. However, it is inefficient for larger datasets with a worst-case and average time complexity of O(n^2). There are other more efficient sorting algorithms for handling larger datasets, like QuickSort, MergeSort, and HeapSort.

3. When should bubble sort be used?

Bubble sort is best used when dealing with a small dataset or a list nearly sorted. It can also be a good choice for educational purposes due to its simplicity.

Test your C programming skills with a Free Quiz

Director of Engineering

Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working â€¦Read More

Need Guidance? We're Here to Help!
+91
*
By clicking, I accept theT&Cand
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.

Talk to our experts. Weâ€™re available 24/7.

Indian Nationals

1800 210 2020

Foreign Nationals

+918045604032

Disclaimer

upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...