Sorting is an essential operation in computer science and programming. Among the various sorting algorithms, Bubble Sort stands out for its simplicity and ease of implementation. In this article, we explore the Bubble Sort algorithm in C, its working, and practical implementation. By understanding this algorithm, you can enhance your grasp of C programming and sorting techniques.
Bubble Sort is a simple sorting algorithm that repeatedly steps through a list, compares adjacent elements, and swaps them if they are in the wrong order. This process continues until the list is sorted.
The algorithm repeatedly compares adjacent elements in the array:
Here’s how Bubble Sort works on an example array:
Pass | Array State |
---|---|
Initial | 5, 3, 8, 6, 2 |
Pass 1 | 3, 5, 6, 2, 8 |
Pass 2 | 3, 5, 2, 6, 8 |
Pass 3 | 3, 2, 5, 6, 8 |
Pass 4 | 2, 3, 5, 6, 8 |
Below is the code to implement Bubble Sort in C:
#include <stdio.h> 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 the elements int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } } void printArray(int arr[], int size) { for (int 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]); printf("Original array: "); printArray(arr, n); bubbleSort(arr, n); printf("Sorted array: "); printArray(arr, n); return 0; }
Original array: 64 34 25 12 22 11 90 Sorted array: 11 12 22 25 34 64 90
Bubble Sort is ideal for:
The main idea is to repeatedly swap adjacent elements if they are in the wrong order, effectively "bubbling" the largest unsorted element to its correct position.
Due to its O(n^2) time complexity, Bubble Sort performs poorly on large datasets compared to more advanced algorithms like Merge Sort or Quick Sort.
Yes, by introducing a flag to check if any swaps occurred during a pass. If no swaps are made, the array is already sorted, and the algorithm can terminate early.
Yes, Bubble Sort is a stable sorting algorithm as it does not change the relative order of equal elements.
The Bubble Sort algorithm is a fundamental technique in C programming. While it is not the most efficient for large datasets, its simplicity and ease of use make it an excellent choice for beginners and for understanding the basics of sorting algorithms. By practicing Bubble Sort and implementing it in various scenarios, you can strengthen your programming skills and understanding of sorting algorithms.
Copyrights © 2024 letsupdateskills All rights reserved