Bubble Sort Implementation in Java
Optimized Bubble Sort in Java with early-exit logic and O(1) space complexity.
Java (17)
2026-01-14
AI Generated
algorithm
sorting
bubble-sort
java
optimization
Description
This snippet provides a robust and optimized implementation of the Bubble Sort algorithm. It includes a flag to detect if any swaps occurred during a pass, allowing the algorithm to terminate early if the collection is already sorted, improving the best-case time complexity to O(n).
Code
public class BubbleSort { /** * Sorts an array of integers using the optimized Bubble Sort algorithm. * Time Complexity: O(n^2) worst/average, O(n) best case. * Space Complexity: O(1). * * @param array The array to be sorted. */ public static void sort(int[] array) { if (array == null || array.length <= 1) { return; } int n = array.length; boolean swapped; for (int i = 0; i < n - 1; i++) { swapped = false; for (int j = 0; j < n - i - 1; j++) { if (array[j] > array[j + 1]) { // Swap elements int temp = array[j]; array[j] = array[j + 1]; array[j + 1] = temp; swapped = true; } } // If no elements were swapped in the inner loop, the array is sorted if (!swapped) { break; } } } public static void main(String[] args) { int[] data = {64, 34, 25, 12, 22, 11, 90}; sort(data); for (int i : data) { System.out.print(i + " "); } }}
Comments
No comments yet. Be the first to comment!
Please login to leave a comment.