Bubble Sort Algorithm Java | Beginner’s Algorithm

Bubble sort algorithm is the simple algorithm which uses swapping technique to sort the elements in the array.

I have a taken an array as arr[ ] = {5, 3, 2, 1, 6} as an example.

Logic – We need to loop over all the elements in the array one by one, if we found that previous elements is larger than then the current element, then we need to swap those elements. Same thing we need to repeat until we reach the end of the array.

Time Complexity – O(n2)

Space Complexity – 1

Algorithm with Separate Method for Bubble Sort

public class Main {
    public static void main(String[] args) {
        int arr[] = {5, 3, 2, 1, 6};

        //print all elements of array
        for (int i : bubbleSort(arr)) {
            System.out.println(i);
        }
    }

    public static int[] bubbleSort(int[] arr) {
        int n = arr.length;
        for (int i = 0; i < n - 1; i++) {
            for (int j = i + 1; j < n; j++) {
                if (arr[i] > arr[j]) {
                    int temp = arr[i];
                    arr[i] = arr[j];
                    arr[j] = temp;
                }
            }
        }
        return arr;
    }
}

Algorithm Inside the Main Method

public class Main {
    public static void main(String[] args) {
        int arr[] = {5, 3, 2, 1, 6};
        int n = arr.length;
        for (int i = 0; i < n - 1; i++) {
            for (int j = i + 1; j < n; j++) {
                if (arr[i] > arr[j]) {
                    int temp = arr[i];
                    arr[i] = arr[j];
                    arr[j] = temp;
                }
            }
        }
        //print all elements of array
        for (int i : arr) {
            System.out.println(i);
        }
    }
}

Leave a Reply

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

WhatsApp Icon Join For Job Alerts