# bubble sort algorithm with Video tutorial

*Bubble sort is sorting algorithm in which 0th element is compare with 1st element and if 0th element is greater than 1st element then they are interchanged.1st element is compare with 2nd element and if 1st element is greater than 2nd element then they are interchanged. and so on. i.e comparing each pair of adjacent items and swapping them if they are in the wrong order. this process will continue until no swap is required.*

Lets take a look at example given in wikipedia.

**First Pass:**

( 5 1 4 2 8 ) –> ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps since 5 > 1.

( 1 5 4 2 8 ) –>( 1 4 5 2 8 ), Swap since 5 > 4

( 1 4 5 2 8 ) –> ( 1 4 2 5 8 ), Swap since 5 > 2

( 1 4 2 5 8 ) –> ( 1 4 2 5 8 ), Now, since these elements are already in order (8 > 5), algorithm does not swap them.

**Second Pass:**

( 1 4 2 5 8 ) –> ( 1 4 2 5 8 )

( 1 4 2 5 8 ) –> ( 1 2 4 5 8 ), Swap since 4 > 2

( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )

( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )

Now, the array is already sorted, but our algorithm does not know if it is completed. The algorithm needs one whole pass without any swap to know it is sorted.

**Third Pass:**

( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )

( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )

( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )

( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )

#include<stdio.h> int main () { int arr[] = { 5, 1, 4, 2, 8 }; bool is_swap = true; int j = 0; int size = sizeof(arr)/sizeof(arr[0]); int tmp; while (is_swap) { is_swap = false; j++; for (int i = 0; i < size - j; i++) { if (arr[i] > arr[i + 1]) { tmp = arr[i]; arr[i] = arr[i + 1]; arr[i + 1] = tmp; is_swap = true; } } } int i=0; for (i;i<size-1;i++) printf("%d ",arr[i]); printf("\n"); return 0; }

## Leave a Reply