Bubble Sort is a comparison based simple sorting algorithm that works by comparing the adjacent elements and swapping them if the elements are not in the correct order. It is an in-place and stable sorting algorithm that can sort items in data structures such as arrays and linked lists.
#include <stdio.h>
void swap(int *arr, int i, int j)
{
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
void bubbleSort(int arr[], int n)
{
for (int i = 0; i < n - 1; i++)
{
// Last i elements are already in place, so the loop will only num n - i - 1 times
for (int j = 0; j < n - i - 1; j++)
{
if (arr[j] > arr[j + 1])
swap(arr, j, j + 1);
}
}
}
int main()
{
int arr[] = {5, 6, 1, 3};
int n = sizeof(arr) / sizeof(arr[0]);
// Calling bubble sort on array arr
bubbleSort(arr, n);
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
return 0;
}
Output
1 3 5 6
Time Complexity: O(n2), where n is the number of items in the list.
Auxiliary Space: O(1)
Working of Bubble Sort Algorithm
Bubble-sort is an in-place and stable sorting algorithm (i.e. the relative order of the elements remains the same after sorting) that can sort items in data structures such as arrays and linked lists. It performs n-1 passes of the array/linked list and in each pass the largest unsorted element is moved to its correct position.
Bubble Sort for Decreasing Order
To modify the bubble sort algorithm for sorting in decreasing order we simply need to move the smallest unsorted element to the end by changing the condition for swapping (i.e. swap the elements if the (i+1)th element is greater than ith element).
Optimization
The bubble sort algorithm may perform all (n-1) passes even if the array is already sorted. Using a swapped flag in the inner loop allows the algorithm to detect if any swaps occurred, stopping early if the array is sorted.
Note: Although this approach improves the performance of bubble sort in cases where the array gets sorted in earlier passes, it does not change its worst-case time complexity.
#include <stdbool.h>
#include <stdio.h>
void swap(int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}
void bubbleSort(int arr[], int n)
{
for (int i = 0; i < n - 1; i++)
{
// swapped variable to signal if there is a swap happened in the inner loop initially set to false
bool swapped = false;
for (int j = 0; j < n - i - 1; j++)
{
if (arr[j] > arr[j + 1])
{
swap(arr + j, arr + j + 1);
// swapped is set to true if the swap is
// done
swapped = true;
}
}
// If no two elements were swapped
// by inner loop, then break
if (swapped == false)
break;
}
}
int main()
{
int arr[] = {5, 6, 1, 3};
int n = sizeof(arr) / sizeof(arr[0]);
// Calling bubble sort on array arr
bubbleSort(arr, n);
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
return 0;
}
Output
1 3 5 6
Time Complexity: O(n2)
Auxiliary Space: O(1)