In this post, we will see how to do sorting ascending and descending using Bubble sort algorithm.

Table of Contents

**What is Bubble sort in Java?**

Bubble sort is a sorting algorithm to sort the data in ascending or descending order by comparing two adjacent elements and swap them if they are not in correct order.

## Bubble sort program for sorting in ascending Order

package demopkg; public class BubbleSort { public static void main(String[] args) { int[] a= {35,18,27,46,23,67,56}; int temp; for(int i = 0; i<a.length; i++) { int flag = 0; for(int j = 0; j< a.length-1-i; j++) { if(a[j]> a[j+1]) { temp = a[j]; a[j] = a[j+1]; a[j+1] = temp; flag=1; } } if(flag==0) { break; } } System.out.print("Sorted Array:"); for(int i=0 ; i<a.length; i++ ) { System.out.print(" "+a[i]); } } }

**Output: **

Sorted Array: 18 23 27 35 46 56 67

**Bubble sort algorithm:**

- Starting from the first index. Compare first two element.
- If first element is greater than the second element then they will swapped, Otherwise we will compare second and third element.
- The above process will go until last element.

Above three steps we will repeat until all elements are not get sorted.

In 2^{nd} iteration again we start comparing element from first index and so on.

### Bubble Sort Time Complexity:

Bubble sort is easy to implement and stable sorting algorithm with time complexity of **O(n2)** in average case and **O(n)** in best case.

**Watch this video for more Bubble Sort in Java:**

Bookmark this post ‘* bubble sort in Java*‘ for future reference.

Enjoy this post? Try these related Posts

**Java Program To Check if String Contains Digits**