Bubble Sort in Java

Bubble Sort in Java in a bubble sorting algorithm, in which elements of the list gradually rise or bubble to their proper location in the array.

Bubble sort algorithms cycle through a list, analyzing pairs of elements from left to right, or beginning to end. If the leftmost element in the pair is less than the rightmost element, the pair will remain in that order. If the rightmost element is less than the leftmost element, then the two elements will be switched. This cycle repeats from beginning to end until a pass in which no switch occurs.

Steps
– take two adjacent elements at a time and compare them.
● if input[i] > input[i+1]
– swap
– repeat until no more swaps are possible.

bubble sort in java

Bubble Sort example in java:-

import java.util.Arrays;

public class BubbleSort {
 
	public static void main(String[] args) {
		int[] unsortedArray = {48, 83, 87, 33, 66, 47, 18, 4, 18, 39};
		System.out.println("Array Before sorting:" +Arrays.toString(unsortedArray));
		System.out.println("Array After sorting: " +Arrays.toString(bubbleSort(unsortedArray)));
	} 

	private static int[] bubbleSort(int[] arr){
		int temp;
        for(int i=0; i < arr.length-1; i++){ 
            for(int j=1; j < arr.length-i; j++){ if(arr[j-1] > arr[j]){
                    temp=arr[j-1];
                    arr[j-1] = arr[j];
                    arr[j] = temp;
                }
            }
            System.out.println((i+1)+"th element swapped: "+Arrays.toString(arr));
        }
        return arr;
    }
}

output:-
bubble sort in java

Leave a Comment