Scroll Progress Bar

Bubble sort

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

Algorithm:
  • Start with the first element of the array.
  • Compare it with the next element.
  • If the next element is smaller, swap them.
  • Move to the next element and repeat steps 2 and 3 until the end of the array is reached.
  • Repeat the above steps for the remaining elements in the array until the whole array is sorted./li>
Sample Code with Explanation and Output:

#include <stdio.h>

void bubbleSort(int arr[], int size) {
    int temp;
    for (int i = 0; i < size - 1; i++) {
        for (int j = 0; j < size - i - 1; j++) {
            // Compare adjacent elements and swap if necessary
            if (arr[j] > arr[j + 1]) {
                temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
            }
        }
    }
}

int main() {
    int arr[] = {64, 34, 25, 12, 22, 11, 90};
    int size = sizeof(arr) / sizeof(arr[0]);

    printf("Original Array: ");
    for (int i = 0; i < size; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");

    // Sort the array using Bubble Sort
    bubbleSort(arr, size);

    printf("Sorted Array: ");
    for (int i = 0; i < size; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");

    return 0;
}
Output:

Original Array: 64 34 25 12 22 11 90
Sorted Array: 11 12 22 25 34 64 90
Explanation:
  • Calculate the size of the array using sizeof() and store it in the variable size.
  • The bubbleSort() function is defined to perform the Bubble Sort algorithm on the array arr.
  • The outer loop runs size - 1 times, as after each iteration, the largest element gets its correct position at the end of the array.
  • The inner loop runs from the beginning of the array up to size - i - 1, as the i largest elements are already in their correct positions after i iterations.
  • Inside the inner loop, compare adjacent elements and swap them if the element on the left is greater than the element on the right.
  • After sorting, print the original and sorted arrays to show the results.

What is Bubble Sort?


Sorting

How does Bubble Sort work?


Comparisons

What is the time complexity of Bubble Sort in the worst case?


Quadratic

What is the main drawback of Bubble Sort?


Efficiency

What type of sorting algorithm is Bubble Sort?


Simple