Download All Shree Lipi Fonts FREE

Bubble sort With code in JAVA/C++/C/Go

What is Bubble sort?

Bubble sort is a simple sorting algorithm that repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order. The pass through the list is repeated until the list is sorted. This sorting algorithm gets its name because smaller elements "bubble" to the top of the list with each pass.

Here is an algorithm of bubble sort- 

  1. Start at the beginning of the list.
  2. Compare the first two elements. If the first is greater than the second, swap them.
  3. Move to the next pair of elements, and so on, continuously making comparisons and swapping if necessary.
  4. After the first pass, the largest element will be in its correct position at the end of the list.
  5. Repeat this process for the remaining elements, each time starting one element earlier.
  6. Continue until no swaps are needed, indicating that the list is sorted.

Implementation of Bubble sort-

static void bubbleSort(int[] array) {
    	int n = array.length;
        for (int i = 0; i < n-1; i++) {
            for (int j = 0; j < n-i-1; j++) {
                if (array[j] > array[j+1]) {
                    // swap array[j] and array[j+1]
                    int temp = array[j];
                    array[j] = array[j+1];
                    array[j+1] = temp;
                }
            }
        }
    }
void bubbleSort(int arr[], int n) {
    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;
            }
        }
    }
}
void bubbleSort(int arr[], int n) {
    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;
            }
        }
    }
}
func bubbleSort(arr []int) {
    n := len(arr)
    for i := 0; i < n-1; i++ {
        for j := 0; j < n-i-1; j++ {
            if arr[j] > arr[j+1] {
                // Swap arr[j] and arr[j+1]
                arr[j], arr[j+1] = arr[j+1], arr[j]
            }
        }
    }
}

Bubble sort complexity-

Time Complexity
Best case Average case Worst case
O(n) O(n2) O(n2)
Space Complexity
O(1)

Thank you for your valuable time!

Hi, I am Kunal Skilled coder with a passion for crafting elegant solutions to complex problems, leveraging expertise to innovate and drive technological advancements.