DEV Community

Cover image for Bubble Sort
Ankit Kumar Meena
Ankit Kumar Meena

Posted on

1

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;
}
Enter fullscreen mode Exit fullscreen mode

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

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs