Understanding and Implementing Bubble Sort in Java

Sorting is one of the most common operations used in computer science. For sorting there are various algorithms available, one such simple sorting algorithm is Bubble sort.

Bubble Sort

Bubble Sort is a simple algorithm that repeatedly iterates through the array, compares adjacent elements one by one, and swaps adjacent elements if they are in the wrong order. The iteration of the array is repeated until the array is sorted.

Bubble Sort Time Complexity

Time complexity of Bubble Sort = O(n2)

Bubble Sort is a simple sorting algorithm but it is not the most efficient sorting algorithm, especially for large data sets.

Bubble Sort Java Implementation

public class BubbleSortJava {
    public static void main(String[] args) {
        int array[] = {27,4,63,8,10};
        BubbleSort(array);
        for(int i=0;i<array.length;i++){
            System.out.println(array[i]);
        }
    }
    public static void BubbleSort(int array[]) {
        for (int i = 0; i < array.length - 1; i++) {
            for (int j = 0; j < array.length - 1 - i; j++) {
                if (array[j] > array[j + 1]) {
                    int temp = array[j];
                    array[j] = array[j + 1];
                    array[j + 1] = temp;
                }
            }}
        }}

Similar Java Tutorials

Leave a Comment