Tutorial Playlist
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 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.
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].
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++) { Â Â |
Here, n is the number of elements in the array arr[]. This code will sort the array in ascending order.
Here's a full implementation of Bubble Sort using a for loop in C:
#include <stdio.h> |
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.
Using a while loop, we can also implement the Bubble Sort algorithm. Here is a simple program for that:
#include <stdio.h> |
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.
Functions allow us to modularise our code. Here is a bubble sort program in C using function.
#include <stdio.h> |
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.
We can also implement Bubble Sort using pointers. Here's an example of how we can do that:
#include <stdio.h> |
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.
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 <stdio.h> |
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.
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:
The Bubble Sort algorithm, despite its simplicity, isn't the most efficient for large datasets. Here's why:
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.
Despite being inefficient for larger datasets, Bubble Sort is straightforward to understand and easy to implement, making it suitable for:
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:
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.
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.
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.
PAVAN VADAPALLI
Popular
Talk to our experts. We’re available 24/7.
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
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 enrolling. upGrad does not make any representations regarding the recognition or equivalence of the credits or credentials awarded, unless otherwise expressly stated. Success depends on individual qualifications, experience, and efforts in seeking employment.
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...