Bubble Sort is the simplest sorting algorithm that works by iterating through the array from the first index to the last index and comparing adjacent elements and then swapping them if they appear in the wrong order. I.e. If the next element is smaller than the current element, they are swapped.

As it iterates for all the array elements with repeatedly swapping the adjacent elements. So this algorithm is not suitable for large data sets as its worst-case complexity are of Ο(n2) where n is the number of items.

Example

Let say we have an array of numbers ” {6, 1 ,3 ,2 ,9}”, and sort the array in ascending order

Step 1 –

{6, 1, 3, 2, 9} → {1, 6, 3, 2, 9} → {1, 3, 6, 2, 9} → {1, 3, 2, 6, 9} → {1, 3, 2, 6, 9}

Step 2 –

{1, 3, 2, 6, 9} → {1, 3, 2, 6, 9} → {1, 2, 3, 6, 9} → {1, 2, 3, 6, 9} → {1, 2, 3, 6, 9}

–Array is sorted but still algorithm will continue

Step 3 –

{1, 2, 3, 6, 9} → {1, 2, 3, 6, 9} → {1, 2, 3, 6, 9} → {1, 2, 3, 6, 9} → {1, 2, 3, 6, 9}

Step 4 –

{1, 2, 3, 6, 9} → {1, 2, 3, 6, 9} → {1, 2, 3, 6, 9} → {1, 2, 3, 6, 9} → {1, 2, 3, 6, 9}

Step 5 –

{1, 2, 3, 6, 9} → {1, 2, 3, 6, 9} → {1, 2, 3, 6, 9} → {1, 2, 3, 6, 9} → {1, 2, 3, 6, 9}

Bubble Sort example in C#