Bubble sort using JAVA

How It Works? Bubble Sort Logic:

  • Compare each pair of elements in the array.
  • Swap them if they are in the wrong order.
  • Repeat this process for each pass until the array is sorted.

Optimization: If no swaps occur during a pass, the array is already sorted, and the loop breaks early.

public class Sorting {
    // Bubble Sort Method
    public static void bubbleSort(int[] array) {
        int n = array.length;
        boolean swapped;

        // Outer loop for each pass
        for (int i = 0; i < n - 1; i++) {
            swapped = false;

            // Inner loop for comparing elements
            for (int j = 0; j < n - 1 - i; j++) {
                if (array[j] > array[j + 1]) {
                    // Swap the elements
                    int temp = array[j];
                    array[j] = array[j + 1];
                    array[j + 1] = temp;

                    swapped = true; // Mark as swapped
                }
            }

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

    // Main method to test the sorting
    public static void main(String[] args) {
        int[] numbers = {64, 34, 25, 12, 22, 11, 90};

        System.out.println("Unsorted array:");
        printArray(numbers);

        bubbleSort(numbers);

        System.out.println("Sorted array:");
        printArray(numbers);
    }

    // Utility method to print the array
    public static void printArray(int[] array) {
        for (int num : array) {
            System.out.print(num + " ");
        }
        System.out.println();
    }
}

Built With

Share this project:

Updates