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)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

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

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay