# Bubble Sort Algorithm with C++ Code | Sorting Algorithms | Data Structures & Algorithms

In this tutorial we understand the working of **bubble sort algorithm** in data structures.

##### **Bubble Sort –**

- Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in wrong order.
- This algorithm is suitable for small data sets
- Its average and worst case complexity are of (
**n^2**) where n is the number of items. - It is known as bubble sort, because with every complete iteration the largest element bubbles up towards the last place or the highest index just like a water bubble rises up to the water surface.

##### Working –

- Step 1 – Starting with the first element(index = 0), compare the current element with the next element of the array.
- Step 2 – If the current element is greater than the next element of the array, swap them.
- Step 3 – If the current element is less than the next element, move to the next element.
- Step 4 – Repeat Step 1 till the list is sorted.

**Bubble Sort Algorithm –**

*declare variables – i, j**loop : i = 0 to n – 1 // outer loop**loop : j = 0 to n -i- 1 // inner loop**if ( a[j]>a[j+1] ) then*- swap a[j] & a[j+1]

*end loop // inner loop*

*end loop // outer loop*

##### **C++ Program to Implement BubbleSort –**

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | #include < iostream > using namespace std; void bubbleSort(int a[]) { for (int i = 0; i < 5; i++) { for (int j = 0; j < (5 - i - 1); j++) { if (a[j] > a[j + 1]) { int temp = a[j]; a[j] = a[j + 1]; a[j + 1] = temp; } } } } int main() { int myarray[5]; int size; cout << "Enter 5 integers in any order: " << endl; for (int i = 0; i < 5; i++) { cin >> myarray[i]; } cout << "Before Sorting" << endl; for (int i = 0; i < 5; i++) { cout << myarray[i] << " "; } bubbleSort(myarray); // sorting cout << endl << "After Sorting" << endl; for (int i = 0; i < 5; i++) { cout << myarray[i] << " "; } return 0; } |

**YouTube video tutorials –**