Javatpoint Logo
Javatpoint Logo

Bubble Sort

Bubble Sort also known as Exchange Sort, is a simple sorting algorithm. It works by repeatedly stepping throughout the list to be sorted, comparing two items at a time and swapping them if they are in the wrong order. The pass through the list is duplicated until no swaps are desired, which means the list is sorted.

This is the easiest method among all sorting algorithms.

BUBBLE SORT (A)
1. for i ← 1 to length [A]
2. for k ← length [A] down to i+1
3. if A[k] <A[k-1]
4. exchange (A[k], A [k-1])

Analysis:

  1. Input: n elements are given.
  2. Output: the number of comparisons required to make sorting.
  3. Logic: If we have n elements in bubble sort, then n-1 passes are required to find a sorted array.
  In pass 1: n-1 comparisons are required
  In pass 2: n-2 comparisons are required
  In pass 3: n-3 comparisons are required
 ............................................................................
 ...............................................................................
  In pass n-1: 1 comparisons is required 
  Total comparisons: T (n) = (n-1) + (n-2) +...........+ 1
                           = DAA Bubble Sort
                           = o (n2)
   Therefore complexity is of order n2 

Example:

Unsorted List: A = {7, 2, 1, 4, 5, 9, 6}

i.e., A [] =

7 2 1 4 3 6 9

And A [] =

7 2 1 3 4 6 9

Then A [] =

7 1 2 3 4 6 9

Then A [] =

1 7 2 3 4 6 9

And A [] =

1 2 7 3 4 6 9

Then A [] =

1 2 3 7 4 6 9

And A [] =

1 2 3 4 7 6 9

And A [] =

1 2 3 4 6 7 9

is the sorted array.


Next TopicSelection Sort




Please Share

facebook twitter google plus pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA