Bubble Sort

0
35
Bubble Sort algorithm explained
Bubble Sort algorithm with explained

Buble sort Overview

Parameter Description
Stable Yes
In place Yes
Best case complexity O(n)
Average case complexity O(n^2)
Worst case complexity O(n^2)
Space complexity O(1)

Bubble Sort Explaination

Buble sort approach

  • Select the first element of the array
  • Compare it with its next element
  • If it is larger than the next element then swap them
  • else do nothing
  • Keep doing this for every index of the array
  • Repeat the above process n times.

The BubbleSort compares each successive pair of elements in an unordered list and inverts the elements if they are not in order.

The following example illustrates the bubble sort on the list {6,5,3,1,8,7,2,4} (pairs that were compared in each step are encapsulated in ‘**’):

After one iteration through the list, we have {5,3,1,6,7,2,4,8}. Note that the greatest unsorted value in the array (8 in this case) will always reach its final position. Thus, to be sure the list is sorted we must iterate n-1 times for lists of length n.

Another example:

Buble sort animation explanation

Buble sort animation explanation

Bubble sort video explanation


Bubble Sort implementation

Bellow, we are going to implement bubble sort algo in several programing languages.

You may also enjoy: Dynamic programming problems tutorial

Implementation in C & C++

C Implementation:

Bubble Sort with pointer:

Implementation of BubbleSort in C++:

Implementation in C#

Bubble sort is also known as Sinking Sort. It is a simple sorting algorithm that repeatedly steps through the list to be sorted, compares each pair of adjacent items and swaps them if they are in the wrong order.

How bubble sort algorithm work step by step
How bubble sort algorithm work step by step

Python Implementation

Implementation in Java

Implementation in Javascript

Thank you for support free4dev, hope this article help you!

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.