## DEV Community

Ankit Kumar Meena

Posted on

# Bubble Sort

## Bubble Sort:

It is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order.

In this algorithm,

1. Traverse from left and compare adjacent elements and the higher one is placed at right side.
2. In this way, the largest element is moved to the rightmost end at first.
3. This process is then continued to find the second largest and place it and so on until the data is sorted.

## C++ Code

``````
#include <bits/stdc++.h>
using namespace std;

void bubbleSort(int arr[], int n)
{
int i, j;
bool swapped;
for (i = 0; i < n - 1; i++) {
swapped = false;
for (j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
swap(arr[j], arr[j + 1]);
swapped = true;
}
}
if (swapped == false)
break;
}
}

void print(int arr[], int size)
{
int i;
for (i = 0; i < size; i++)
cout << " " << arr[i];
}

int main()
{
int arr[] = { 23, 45, 65, 23, 57, 88 };
int N = sizeof(arr) / sizeof(arr[0]);
bubbleSort(arr, N);
cout << "Sorted array: \n";
print(arr, N);
return 0;
}
``````

Time Complexity: O(N2)
Auxiliary Space: O(1)