Bubble Sort in Java With Examples

Java Sorting is one of the many aspects of java interview questions. In this post, we will see java bubble sort example and write a program for bubble sort.

Bubble sort is also known as the exchange sort. It is the simplest algorithm for sorting numbers.

Bubble Sort Algorithm

  • In bubble sort, the array of integers is traversed from index 0 to length-1.
  • The value at 0th position is compared with the value at 1st position and if the later is small, it’s swapped.
  • The comparison is moved from the 0th index to length-1 index so that after the first iteration, the last index has the biggest value.
  • The same process is repeated again from 0th to length-1 index. After (length-1) iteration, the array is sorted.
  • In worst-case, the complexity of bubble sort is O(n2) and in best-case, the complexity of bubble sort is Ω(n).

Bubble Sort in Java

Here is the implementation of Bubble Sort in Java program.

The above program is for sorting in ascending as well as descending order using bubble sort algorithm.

Output of the above program is:

As we can see that in every iteration, the last index is getting sorted and it takes (array length – 1) iterations for sorting.

You can checkout complete example and more sorting algorithm implementations at our GitHub Repository.

By admin

Leave a Reply

%d bloggers like this: