C Bubble Sort

Summary: this tutorial explains how the bubble sort algorithm works and shows you how to implement the bubble sort in C.

c bubble sortIntroduction to the bubble sort algorithm

Bubble sort is a simple sorting algorithm. The bubble sort works by arranging adjacent elements repeatedly if they are not in the correct order. When no exchange is needed, the list is sorted.

By doing this, the smaller element bubble to the top, that why this sorting technique is called bubble sort.

Bubble sort is the simplest sorting algorithm is are easy to understand and quick to implement. However, in practice, it is not recommended.

The complexity of the bubble sort algorithm is O(n2). Its efficiency decreases dramatically when the number of elements in the unsorted list increases.

Among the  O(n2) sorting algorithms, the insertion sort is more efficient than the bubble sort.

C bubble sort implementation

The following is the C program for bubble sorting demonstration. We use the bubble sort technique to sort an array of integers.

#include <stdio.h> #include <stdlib.h> #define SIZE 10 void swap(int *x,int *y); void buble_sort(int a[], const int n); void display(int a[],int size); void main() { int a[SIZE] = {8,5,2,3,1,6,9,4,0,7}; int i; printf("The array before sorting is:\n"); display(a,SIZE); buble_sort(a,SIZE); printf("The array after sorting using bubble sorting algorithm:\n"); display(a,SIZE); } void swap(int *x,int *y) { int temp; temp = *x; *x = *y; *y = temp; } void buble_sort(int a[],const int size) { int i,j; for(i=0; i<(size-1); i++) { for(j=0; j<(size-(i+1)); j++) { { if(a[j] > a[j+1]) swap(&a[j],&a[j+1]); } } } } void display(int a[],const int size) { int i; for(i = 0; i < size; i++) printf("%d ",a[i]); printf("\n"); }
Code language: C++ (cpp)

In this tutorial, you have learned about the bubble sort algorithm and how to implement it in C.

Was this tutorial helpful ?