Bubble Sort in C. Sorting is a fundamental operation in computer science, where elements in a collection are arranged in a specified order among the various sorting algorithms, bubble sort is one of the simplest and straight forward methods. In this article, we will explore bubble sorting and write a C program for Bubble sorting.
Table of Contents
Understanding Bubble Sort
Bubble Sort is one of the simplest sorting algorithms, known for its concept and ease of implementation rather than its efficiency. The core logic of Bubble Sort involves nested loops and the methodical comparison of elements. Bubble sort compares each pair of adjacent elements, and swaps them if they are in the wrong order.
C Program for Bubble Sort
#include <stdio.h>
void buubleSort(int arr[], int n)
{
int temp;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < (n - i - 1); j++)
{
if (arr[j] > arr[j + 1])
{
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
void main()
{
int array[] = {90, 75, 87, 48, 2, 67, 23, 56, 98, 78, 67, 56};
int n = sizeof(array) / sizeof(array[0]);
printf("Array before sorting\n");
for (int i = 0; i < n; i++)
{
printf("%d ", array[i]);
}
buubleSort(array, n);
printf("\nArray after sorting\n");
for (int i = 0; i < n; i++)
{
printf("%d ", array[i]);
}
}
Output
Bubble Sort Time Complexity
Best Case Scenario
The time complexity of Bubble sort in the best-case scenario is O(n)
. The best-case scenario occurs when the input array is already sorted. In this case Bubble sort only needs to make one alteration to the array to verify that it is sorted.
Average and Worst Case Scenario
The time complexity of Bubble sort in the best-case scenario is O(n
^2). This complexity occurs because, for each element in the array, Bubble sort must compare it to every other element, leading to a performance that degrades rapidly as the size of the input array increases. The worst case is encountered when the array is sorted in reverse order.
Bubble Sort Space Complexity
The space complexity of the Bubble sort is O(n), It is one of the Bubble sort advantages. Bubble sort operates by swapping elements in place within an array, requiring no additional storage space.
Happy Coding & Learning
1 thought on “Bubble Sort in C”