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!