Home page

Saturday, June 17, 2023

Bubble sort in JAVA

Bubble sort is a simple sorting algorithm that repeatedly compares adjacent elements 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 list. Bubble sort is not efficient for large datasets but can be useful for small datasets or as an educational tool to understand sorting algorithms.

The purpose of using bubble sort is to sort a given array or list in ascending or descending order. It is straightforward to implement and does not require any additional data structures. However, due to its simplicity, bubble sort has a time complexity of O(n^2), making it inefficient for large datasets. There are more efficient sorting algorithms available, such as merge sort or quicksort, that are generally preferred for practical use.

Here's an example of how you can implement bubble sort in Java:

public class BubbleSortExample {

    public static void main(String[] args) {

        int[] arr = {5, 2, 8, 12, 3};

        System.out.println("Original array: ");

        printArray(arr);

        bubbleSort(arr);

        System.out.println("Sorted array: ");

        printArray(arr);

    }

    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 printArray(int[] arr) {

        for (int element : arr) {

            System.out.print(element + " ");

        }

        System.out.println();

    }

}

In this example, we have an array arr containing integers. We first print the original array using the printArray() method.

The bubbleSort() method implements the bubble sort algorithm. It iterates through the array using nested loops, comparing adjacent elements and swapping them if they are in the wrong order. This process is repeated until the entire array is sorted.

Finally, we print the sorted array using the printArray() method.

Output:
Original array: 
5 2 8 12 3 
Sorted array: 
2 3 5 8 12 

As shown in the example, bubble sort compares adjacent elements and swaps them if they are out of order. This process is repeated until the array is sorted. Bubble sort is not the most efficient sorting algorithm, but it can be useful for small datasets or educational purposes.

No comments:

Post a Comment