Bubble Sort.

I always wanted to blog something like this for a long time. Because whenever I used to learn the algorithm of bubble sort, I used to forget it often and had to by-heart it at times as well. But since now I know it better as well as from next semester onwards we are going to have data structures as a core and I thought I will blog some of the major concepts I would learn there and let this be its stepping stone. (Also, this is what happens when boredom strikes :P)

So let’s get started 🙂 I’m much comfortable with C++ so I would stick on to that to explain how things work.

First of all, Bubble Sort is an algorithm which is used to sort N elements that are given in a memory. It is named thus because, after each iteration the largest number in the array or the list bubbles up to the top, just like the bubbles in the water 😉

Here is the code for it on how it works 🙂

#include <iostream>
using namespace std;

//Function for Bubble Sort
void bubble_sort (int arr[], int n)
  for (int i = 0; i < n; i++)
    for (int j = 1; j < n - i; j++)
      if (arr[j] > arr[j + 1])
        int temp = arr[j];
        arr[j] = arr[j + 1];
        arr[j + 1] = temp;

int main()
  int ar[10], n;

  cout << "Enter the number of elements you want to sort\n";
  cin >> n;

  bubble_sort (ar, n);

  cout << "Sorted Array is : " << endl; 

  for (int i = 0; i < n; ++i)
    cout << input_ar[i] << " ";

  return 0;

Let me give this might give you a better view of it. Actually, this is the way at what bubble sort alogrithm uses to sort each of its elements and this image shoes how its done in each iteration.


So that’s it guys 🙂



Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s