• November 20, 2024
Bubble Sort

How to Implement Bubble Sort in Java?

Bubble Sort is a simple sorting algorithm that repeatedly compares adjacent elements in an array and swaps them if they are in the wrong order. The algorithm gets its name from the way smaller elements “bubble” to the top of the array.

The basic idea of the Bubble Sort algorithm is as follows:

  1. Compare the first two elements of the array. If the first element is greater than the second element, swap them.
  2. Move to the next pair of elements (i.e., the second and third elements) and repeat step 1.
  3. Continue this process for all pairs of adjacent elements in the array until the end of the array is reached.
  4. If any swaps were made during the previous pass through the array, repeat steps 1-3 until no more swaps are needed (i.e., the array is sorted).

Bubble Sort is a simple algorithm to understand and implement, but it is not very efficient for large arrays. It has a time complexity of O(n^2), which means that the time it takes to sort the array increases rapidly as the size of the array grows. However, Bubble Sort is still useful for small arrays or for educational purposes to teach the basic concepts of sorting algorithms.

The following implementation takes an array of integers as input and sorts them in ascending order using the Bubble Sort algorithm. The algorithm works by comparing adjacent elements of the array and swapping them if they are in the wrong order. The process is repeated until the entire array is sorted.

public class BubbleSort {
public static void main(String[] args) {
int[] arr = {64, 34, 25, 12, 22, 11, 90};

    bubbleSort(arr);

    System.out.println("Sorted array:");
    for (int i = 0; i < arr.length; i++) {
        System.out.print(arr[i] + " ");
    }
}

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]) {
                int temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
            }
        }
    }
}

}

Leave a Reply

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