Bubble Sort Algorithm in Java

 

 

Overview

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. The pass through the list is repeated until the list is sorted.

Its average and worst-case time complexity is O(n²), where n is the number of items being sorted. Despite its inefficiency on large lists, it is a popular introductory algorithm.

Java Implementation


public class BubbleSort {
    
    /**
     * This method sorts an array using the Bubble Sort algorithm.
     *
     * @param arr The array of integers to be sorted.
     */
    public static void bubbleSort(int[] arr) {
        int n = arr.length;
        boolean swapped;

        // Traverse through all array elements
        for (int i = 0; i < n - 1; i++) {
            swapped = false;

            // Last i elements are already in place
            for (int j = 0; j < n - i - 1; j++) { // Compare adjacent elements if (arr[j] > arr[j + 1]) {
                    // Swap if they are in the wrong order
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                    swapped = true;
                }
            }

            // If no elements were swapped, the array is sorted
            if (!swapped) break;
        }
    }

    /**
     * Main method to execute the bubble sort.
     *
     * @param args Command line arguments.
     */
    public static void main(String[] args) {
        int[] array = {64, 34, 25, 12, 22, 11, 90};
        
        System.out.println("Original array:");
        printArray(array);
        
        bubbleSort(array);
        
        System.out.println("Sorted array:");
        printArray(array);
    }

    /**
     * This method prints the elements of the array.
     *
     * @param arr The array to be printed.
     */
    public static void printArray(int[] arr) {
        for (int value : arr) {
            System.out.print(value + " ");
        }
        System.out.println();
    }
}
        

Program Structure

The program consists of the following main components:

  • bubbleSort Method: This method takes an array as input and sorts it using the Bubble Sort algorithm.
  • main Method: This is the entry point of the program, where an array is defined, and the sorting function is called.
  • printArray Method: A utility method to display the elements of the array before and after sorting.

Usage

To run this program, copy the code into a file named BubbleSort.java and compile it using a Java compiler. After compiling, execute the program, and it will display the original and sorted arrays.

 

Leave a Reply

Your email address will not be published. Required fields are marked *