Bubble Sort Java Code Explained

5 min read Jun 24, 2024
Bubble Sort Java Code Explained

Bubble Sort in Java: A Step-by-Step Explanation

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.

Here's a Java implementation of bubble sort along with a detailed explanation:

public class BubbleSort {

    public static void bubbleSort(int[] arr) {
        int n = arr.length;
        for (int i = 0; i < n - 1; i++) {
            for (int j = 0; j < n - i - 1; j++) {
                if (arr[j] > arr[j + 1]) {
                    // Swap arr[j] and arr[j+1]
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }
        }
    }

    public static void main(String[] args) {
        int[] data = {5, 1, 4, 2, 8};
        System.out.println("Unsorted Array:");
        printArray(data);

        bubbleSort(data);

        System.out.println("\nSorted Array:");
        printArray(data);
    }

    public static void printArray(int[] arr) {
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + " ");
        }
    }
}

Understanding the Code:

1. bubbleSort(int[] arr) Function:

  • This function takes an integer array arr as input.
  • It uses two nested loops to iterate through the array:
    • The outer loop (i) controls the number of passes.
    • The inner loop (j) compares adjacent elements within the unsorted portion of the array.
  • Comparison and Swapping:
    • Inside the inner loop, if (arr[j] > arr[j + 1]), the code checks if the current element is greater than the next element.
    • If true, the elements are swapped using a temporary variable temp.
  • The algorithm continues to compare and swap elements until the largest element "bubbles up" to the end of the unsorted portion.

2. main(String[] args) Function:

  • This is the entry point of the program.
  • It creates an unsorted array data.
  • Calls the bubbleSort() function to sort the array.
  • Prints the sorted array using printArray().

3. printArray(int[] arr) Function:

  • This function iterates through the array and prints each element.

How Bubble Sort Works:

  1. Pass 1:
    • The first pass compares all adjacent elements in the array.
    • The largest element is moved to the end of the array after multiple swaps.
  2. Pass 2:
    • The second pass compares all adjacent elements except the last one (which is now the largest and in its correct position).
    • The second largest element is moved to its correct position (second to last).
  3. Subsequent Passes:
    • This process continues until the entire array is sorted.

Time Complexity:

  • Best Case: O(n) - when the array is already sorted.
  • Average Case: O(n^2) - when the array is in random order.
  • Worst Case: O(n^2) - when the array is sorted in reverse order.

Advantages:

  • Easy to understand and implement.
  • In-place sorting: It does not require any additional memory.

Disadvantages:

  • Inefficient for large datasets.
  • Not suitable for real-world applications.

Conclusion:

Bubble sort, while simple, is not a practical sorting algorithm for most applications due to its poor time complexity. However, it serves as a good starting point for understanding the basics of sorting algorithms.

Latest Posts