Bubble Sort

Bubble Sort is a simple sorting Algorithm that works through repeatedly comparing the each pair of adjacent item and swapping them if they are in the wrong order, It pass through the list until no swaps are needed that means list is sorted. It’s not at all the preferred algorithm as it’s not efficient for sorting large lists.
A simple animation showing Bubble sort might help you to understand better.
Bubble Sort

import java.util.Random;


public class BubbleSort {
	public static void main(String ar[]){
		int n=10;
		Random rand=new Random();
		int[] array=new int[n];
		for(int i=0;i<n;i++){
			array[i]=rand.nextInt(100);
		}
		System.out.println("Array Before Sorting: \n");
		for(int i=0;i<n;i++){
			System.out.print(array[i]+" ");
		}
		bubbleSort(array);
		System.out.println("\n\nArray After Sorting: \n");
		for(int i=0;i<n;i++){
			System.out.print(array[i]+" ");
		}
	}

	private static void bubbleSort(int[] array) {
		for(int i=0;i<array.length;i++){
			for(int j=0;j<array.length-1;j++){
				if(array[j]>array[j+1]){
					int temp=array[j];
					array[j]=array[j+1];
					array[j+1]=temp;
				}
			}
		}
	}
}

Leave a comment