Bubble Sort

Table of Contents

Related Tutorials

Bubble sort is one of the simplest sorting algorithms. To sort an array using bubble sort,  we will compare every two elements of the array, If these two are already sorted, we will do nothing, otherwise swap them. After doing this length times array will be sorted.

Bubble sort explanation with example

Let array is

4, 2, 3, 5, 1

We are going to sort this array using Bubble sort.
For every iteration from 1 to 4, we will check if adjacent elements are sorted or not. If not then we will swap them.

Bubble sort using C

#include <stdio.h>
int main() {
    int arr[5]={4, 2, 3, 5, 1};
    for(int i=1;i<5;i++)
    {
        for(int j=1;j<5;j++)
        {
            if(arr[j]<arr[j-1])
            {
                int tmp=arr[j];
                arr[j]=arr[j-1];
                arr[j-1]=tmp;
            }
        }
    }
    for(int i=0;i<5;i++)
    {
        printf("%d ", arr[i]);
    }
    return 0;
}


Bubble sort using C++

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

int main() {
    int arr[5]={4, 2, 3, 5, 1};
    for(int i=1;i<5;i++)
    {
        for(int j=1;j<5;j++)
        {
            if(arr[j]<arr[j-1])
            {
                int tmp=arr[j];
                arr[j]=arr[j-1];
                arr[j-1]=tmp;
            }
        }
    }
    for(int i=0;i<5;i++)
    {
        cout<<arr[i]<<" ";
    }
    return 0;
}


Bubble sort using python

arr=[4, 2, 3, 5, 1]
for _ in range(len(arr)):
    for i in range(len(arr)-1):
        if(arr[i+1]<arr[i]):
            arr[i+1], arr[i]=arr[i], arr[i+1];

print(arr)

Bubble sort in java

import java.util.Arrays;
class Sort{
    public static void main(String[] args) {
        int[] arr={4, 2, 3, 5, 1};
        for(int i=0;i<5;i++)
        {
            for(int j=1;j<5;j++)
            {
                if(arr[j]<arr[j-1])
                {
                    int tmp=arr[j];
                    arr[j]=arr[j-1];
                    arr[j-1]=tmp;
                }
            }
        }
        System.out.println(Arrays.toString(arr));
    }
}


Bubble sort in Javascript

var arr=[4, 2, 3, 5, 1];
for(var i=0;i<5;i++)
{
    for(var j=1;j<5;j++){
        if(arr[j]<arr[j-1])
        {
            [ arr[j], arr[j-1] ]=[ arr[j-1], arr[j] ];
        }
    }
}
console.log(arr)


Share The Tutorial With Your Friends
Facebook
Twitter
LinkedIn
Email
WhatsApp
Skype