Bubble Sort in Java

Bubble sort repetitively compares adjacent pairs of elements and swaps if necessary.

Bubble Sort Steps

1. Scan the array, swapping adjacent pair of elements if they are not in relative order. This bubbles up the largest element to the end.
2. Scan the array again, bubbling up the second largest element.
3. Repeat until all elements are in order.

Example

When i = 5
Array = {40, 30, 50, 20, 60, 10}; 
Array = {30, 40, 50, 20, 60, 10}; j=0; Swap Left(40) > Right(30)
Array = {30, 40, 50, 20, 60, 10}; j=1; No Swap Left(40) < Right(50)
Array = {30, 40, 20, 50, 60, 10}; j=2; Swap Left(50) > Right(20)
Array = {30, 40, 20, 50, 60, 10}; j=3; No Swap Left(50) < Right(60)
Array = {30, 40, 20, 50, 10, 60}; j=4; Swap Left(60) > Right(10)

When i = 4
Array = {30, 40, 20, 50, 10, 60}
Array = {30, 40, 20, 50, 10, 60}; j = 0; No Swap, Left(30) < Right(40)
Array = {30, 20, 40, 50, 10, 60}; j = 1; Swap, Left(40) > Right(20)
Array = {30, 20, 40, 50, 10, 60}; j = 2; No Swap, Left(40) < Right(50)
Array = {30, 20, 40, 10, 50, 60}; j = 3; Swap, Left (50) > Right (10)

When i = 3
Array = {30, 20, 40, 10, 50, 60};
Array = {20, 30, 40, 10, 50, 60}; j = 0; Swap, Left (30) > Right(20)
Array = {20, 30, 40, 10, 50, 60}; j = 1; No Swap, Left (30) < Right (40)
Array = {20, 30, 10, 40, 50, 60}; j = 2; Swap Left(40) > Right (10)

When i = 2 
Array = {20, 30, 10, 40, 50, 60}
Array = {20, 30, 10, 40, 50, 60}; j = 0; No swap; Left(20) < Right(30)
Array = {20, 10, 30, 40, 50, 60}; j = 1; Swap; Left(30) > Right(10)

When i = 1
Array = {20, 10, 30, 40, 50, 60};
Array = (10, 20, 30, 40, 50, 60); J = 1, Swap; Left(20) > Right(10)

Here outer loop i iterate n times and innter loop iterate n/2 times. Total Time t(n) = n * (n/2) = O(n^2)

package com.seleniumtest;

public class BubbleSortDemo 
{
	public void bubbleSort(int[] inputArray)
	{
		int n = inputArray.length;
		
		for(int i = n-1; i >= 0; i--)
		{
			System.out.println("\n" + "Value of i:"+i+"\n");
			for (int j = 0; j <= i-1; j++)
			{
				System.out.println("Value of j:"+j);
				if(inputArray[j] > inputArray[j+1])
				{
					int temp = inputArray[j];
					inputArray[j] = inputArray[j+1];
					inputArray[j+1] = temp;
				}
			}
		}
	}
	
	public void printArray(int[] inputArray)
	{		
		for(int i = 0; i < inputArray.length; i++)
		{
			System.out.print(inputArray[i]+" ");
		}
	}
	
	public static void main(String args[])
	{
		int[] arr = {40, 30, 50, 20, 60, 10};
		
		BubbleSortDemo bsd = new BubbleSortDemo();
		bsd.bubbleSort(arr);
		System.out.println("Sorted Array");
		bsd.printArray(arr);
	}

}