Bubble Sort is the most simple form of sorting algorithm based on comparisons. It works by repeatedly stepping through the list of items such as an array and swapping the two adjacent elements if they are in a different order.
This algorithm has no such real-life uses due to its poor performance and is used primarily as an educational tool to teach students about sorting concepts.
Take a look at this video explaining Bubble Sort Algorithm in two minutes.
Bubble Sort Algorithm Performance
Bubble sort algorithm is the worst performing algorithm and most of the other sorting algorithms have a better worst-case or average complexity, often O(n log n).
Worst Case and Average Case Complexity: O(n2)
Best Case Time Complexity: O(n)
Bubble Sort Program
The following C program reads an integer array and prints it on the screen. It then sorts the array using bubble sort and print it again.
#include <stdio.h> #define NMAX 10 int getIntArray(int a[], int nmax, int sentinel); void printIntArray(int a[], int n); void bubbleSort(int a[], int n); int main(void) { int x[NMAX]; int hmny; int who; int where; hmny = getIntArray(x, NMAX, 0); if (hmny==0) printf("This is the empty array!\n"); else{ printf("The array was: \n"); printIntArray(x,hmny); bubbleSort(x,hmny); printf("The sorted array is: \n"); printIntArray(x,hmny); } } void printIntArray(int a[], int n) { int i; for (i=0; i<n; ){ printf("\t%d ", a[i++]); if (i%5==0) printf("\n"); } printf("\n"); } int getIntArray(int a[], int nmax, int sentinel) { int n = 0; int temp; do { printf("Enter integer [%d to terminate] : ", sentinel); scanf("%d", &temp); if (temp==sentinel) break; if (n==nmax) printf("array is full\n"); else a[n++] = temp; }while (1); return n; } void bubbleSort(int a[], int n) { int lcv; int limit = n-1; int temp; int lastChange; while (limit) { lastChange = 0; for (lcv=0;lcv<limit;lcv++) if (a[lcv]>a[lcv+1]) { temp = a[lcv]; a[lcv] = a[lcv+1]; a[lcv+1] = temp; lastChange = lcv; } limit = lastChange; } }
Output of the Bubble Sort Program
Enter integer [0 to terminate] : 3 Enter integer [0 to terminate] : 4 Enter integer [0 to terminate] : 6 Enter integer [0 to terminate] : 2 Enter integer [0 to terminate] : 1 Enter integer [0 to terminate] : 8 Enter integer [0 to terminate] : 6 Enter integer [0 to terminate] : 9 Enter integer [0 to terminate] : 0 The array was: 3 4 6 2 1 8 6 9 The sorted array is: 1 2 3 4 6 6 8 9
See also: Shell Sort, Quick Sort, Insertion Sort, Selection Sort