Bubble Sort Algorithm - The Coding Shala

Home >> Algorithms >> Bubble Sort

Bubble Sort

The Bubble Sort algorithm is the simplest algorithm to sort a given array. The Bubble sort algorithm works by repeatedly swapping the adjacent elements if they are in the wrong order.

Working of Bubble Sort Algorithm

In the Bubble sort algorithm, we use two loops that run n times, n is the size of the array. Every time in the inner loop we check the order of two adjacent elements if they are not in the order we swap them. 

We can optimize this algorithm a little bit. In the above mention approach, both the loops always run n time if the given array is sorted. We can take a boolean array set is false and check if there are no two element swaps in the inner loops means out array is sorted and we break the loop.

Time Complexity of Bubble Sort

The time complexity of the Bubble Sort algorithm is O(N*N), N is the size of a given array.

The space used is O(1).

Bubble Sort Algorithm Java Program

The following is the Java Program of Bubble sort algorithm:
Java Code:

import java.util.Arrays;

//bubble sort
//the coding shala

class Main{
 
 public static void bubble_sort(int[] input) {
  for(int i=0; i<input.length; i++) {
   boolean swap = false;
   for(int j=0;j<input.length-1;j++) {
    if(input[j+1]<input[j]) {
     int tmp = input[j+1];
     input[j+1] = input[j];
     input[j] = tmp;
     swap = true;
    }
   }
   if(swap == false) break;
  }
 }
 
 public static void main(String[] args) {
  int[] input = {1,5,3,2,8,7,6,4};
  int len = input.length;
  bubble_sort(input);
  for(int i=0;i<len;i++) {
   System.out.print(input[i]+" ");
  }
 }
}


Other Posts You May Like
Please leave a comment below if you like this post or found some error, it will help me to improve my content.

Comments

Popular Posts from this Blog

Shell Script to find sum, product and average of given numbers - The Coding Shala

Shell Script to Create a Simple Calculator - The Coding Shala

Richest Customer Wealth LeetCode Solution - The Coding Shala

New Year Chaos Solution - The Coding Shala

Add two numbers in Scala - The Coding Shala