Bubble Sort in Java

In this tutorial you will learn about bubble sort in Java.

In bubble sort algorithm each element is compared with adjacent element and are swapped if not in correct order. It is one of the simplest but worst sorting algorithm. It is suitable for sorting small list of numbers.

As bubbles come up on surface in water, in the same way the lighter or smaller elements come forward and heavier or bigger elements goes back.

Below image shows how bubble sort algorithm works.

Bubble Sort in Java

Time Complexity

Worst Case: O (n2)

Average Case: O (n2)

Best Case: O (n)

 

Program for Bubble Sort in Java

Here is a java program to sort an array using bubble sort.

 

Output

Enter size of array:
5

Enter elements of array:
4 7 8 5 6

Sorted array is:
4 5 6 7 8

Leave a Reply

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