# Bubble Sort in C++

Today, We want to share with you Bubble Sort in C++. The C ++ bubble sequence is a way of sorting the values ​​of an array. Bubble sorting is a technique for sorting a row, or we can sort a list of several numbers. This sorting algorithm is also called the sinking sequence. We will implement the C ++ bubble deployment program to demonstrate how we can apply it in real-life applications.

## Bubble Sort in C++

``````#include<iostream>
using namespace std;
void swapping(int &a, int &b) {      //swap the content of a and b
int temp;
temp = a;
a = b;
b = temp;
}
void display(int *array, int size) {
for(int i = 0; i<size; i++)
cout << array[i] << " ";
cout << endl;
}
void bubbleSort(int *array, int size) {
for(int i = 0; i<size; i++) {
int swaps = 0;         //flag to detect any swap is there or not
for(int j = 0; j<size-i-1; j++) {
if(array[j] > array[j+1]) {       //when the current item is bigger than next
swapping(array[j], array[j+1]);
swaps = 1;    //set swap flag
}
}
if(!swaps)
break;       // No swap in this pass, so array is sorted
}
}
int main() {
int n;
cout << "Enter the number of elements: ";
cin >> n;
int arr[n];     //create an array with given number of elements
cout << "Enter elements:" << endl;
for(int i = 0; i<n; i++) {
cin >> arr[i];
}
cout << "Array before Sorting: ";
display(arr, n);
bubbleSort(arr, n);
cout << "Array after Sorting: ";
display(arr, n);
}``````
##### 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.

## Output

``````Enter the number of elements: 6
Enter elements:
56 98 78 12 30 51
Array before Sorting: 56 98 78 12 30 51
Array after Sorting: 12 30 51 56 78 98``````

Read Also: PHP Program To Reverse a String