Implement Bubble sort in java

If you want to practice data structure and algorithm programs, you can go through data structure and algorithm interview questions.

In this post, we will see how to implement Bubble sort in java. Bubble sort is also known as sinking sort.Bubble sort is a comparison based sorting algorithm and is very easy to implement.

Bubble sort algorithm:

Bubble sort works by iterating first element to last element, comparing two adjacent elements and swapping them if they are not in correct order. Each iteration places next larger value to its correct place.

Why bubble sort is called bubble sort or sinking sort(From wikipedia):

Bubble sort can be done in ascending order or descending order.
Reason for being called Sinking sort:
The larger values might be regarded as heavier and therefore be seen to progressively sink to the bottom of the list
Reason for being called Bubble sort:
The smaller values might be regarded as lighter and therefore be seen to progressively bubble up to the top of the list

Bubble sort example:

I have printed intermediate steps to understand it better:

When you run above program, you will get following output:

You may notice that each iteration places next larger element to its correct place.


Best case: O(n)
Average case: O(nˆ2)
Worst case: O(nˆ2)
To understand more about complexity,please go through complexity of algorithm.

Add Comment