Bubble Sort – Java

Sorting is one of the major required feature for any application during implementation of any business logic.

There are different types of sorting in place based on performance, speed, cost of operation.

One of simplest and easy algorithm is Bubble Sort Algorithm which is an easy one to understand/implement for any quick implementation.

Sorting a List of items [10, 5, 8, 6 , 4] needs each item to be compared with another item in the list.

Bubble Sort Algorithm:

  • Take the 1st position number and compare with all the items in the list. (If other number less than 1st Position number, swap the position of numbers)
  • Iterate the above step, n times.,

Result:

Time Complexity -> O(N2)

Bubble Sort Comparison Explained with the Example

Take the above List of items.
Since the length of items is 5, there will be 5 iteration for each element to compare with each of the number in the list.
[10, 5, 8, 6, 4]

  • First Position Number comparing Iteration:
    1. Take the number in the first position(10) and compare with all the other numbers [5, 8, 6, 4], if greater then swap it.
    2. For example, when comparing, 10>5 , then swap the numbers and list will be like below.
      1. [10, 5, 8, 6, 4] —-> [5, 10, 8, 6, 4] , 10 and 5 is compared… swapped since 10>5.
    3. Now 5 becomes first position number., so start compare with further numbers one by one.
      1. [5, 10, 8, 6, 4] —-> [5, 10, 8, 6, 4] , 5 and 8 is compared.. no swap.,
      2. [5, 10, 8, 6, 4] —-> [5, 10, 8, 6, 4] , 5 and 6 is compared.. no swap.,
      3. [5, 10, 8, 6, 4] —-> [4, 10, 8, 6, 5] , 5 and 4 is compared.. swapped since 5 > 4.,

Repeat the above step n times, so that lowest value numbers will be moved to the left of the List.

Leave a Reply

Your email address will not be published. Required fields are marked *