Java Program to sort an array using the bubble sort algorithm

Bubble sort is a simple sorting algorithm that repeatedly steps through the list compares adjacent elements and swaps them if they are in the wrong order. This process continues until the entire list is sorted. Despite being inefficient on large lists bubble sort can be useful for educational purposes and small datasets due to its simplicity.


Java code : 

public class BubbleSort {
    
    // Function to perform bubble sort on an array
    public static void bubbleSort(int[] arr) {
        int n = arr.length;       
        // Traverse through all elements of the array
        for (int i = 0; i < n - 1; i++) {    
            // Last i elements are already sorted
            // so we iterate through only unsorted elements
            for (int j = 0; j < n - i - 1; j++) {              
                // If the current element is greater than the next element
                if (arr[j] > arr[j + 1]) {
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }
        }
    }
    public static void main(String[] args) {
        // Sample array to be sorted
        int[] arr = {64, 34, 25, 12, 22, 11, 90}; 
        // Perform bubble sort on the array
        bubbleSort(arr);
        // Print the sorted array
        System.out.println("Sorted array:");
        for (int num : arr) {
            System.out.print(num + " ");
        }
    }
}
Output
Sorted array: 11 12 22 25 34 64 90

Explanation:

  • The bubbleSort function takes an integer array arr as input and performs the bubble sort algorithm on it.
  • It starts by iterating through all elements of the array using outer loop (i).
  • Within each iteration of the outer loop it iterates through the unsorted elements of the array using the inner loop (j).
  • For each pair of adjacent elements if the current element is greater than the next element they are swapped.
  • This process is repeated until the entire array is sorted.
  • In the main method we define a sample array arr to be sorted using the bubble sort.
  • We call the bubbleSort function with this array, which sorts the array in ascending order.
  • Finally, we print the sorted array to the console.