Bubble Sort

  • Bubble sort is the simplest algorithm to sort elements in ascending or descending order.
  • This approach works by repeatedly swapping the adjacent elements if they are not in order.
  • The smallest element moves to the front. The movement of array elements is just like the movement of an air bubble in water, which is why it is called bubble sort.
  • It is efficient only for smaller-sized data and is not suitable for large data sets.
  • Video Lecture

    Bubble Sort Operation

    Bubble Sort – Iteration/Passes

  • n - number of elements in the array.
  • The number of iterations or passes is n-1; the bubble sort algorithm is executed for n-1 iterations.
  • In each iteration, the largest element is moved to the last location.
  • During the first iteration, the first largest element is moved to the last location and stored in the correct place.
  • During the second iteration, the second largest element is moved to the last location at the correct place.
  • This process is repeated for n-1 iterations for n elements.
  • Algorithm

    BubbleSort(arr[0]..arr[n-1])

    Input: Array arr contains n elements in unsorted order.

    Output: Array arr contains n elements in sorted order.

    Step 1: Initialize i = 0.

    Step 2: The for loop variable i varies from 0 to n-2.

    Step 3: The for loop variable j varies from 0 to n-2-i.

    Step 4: If arr[j] > arr[j+1], then swap arr[j] and arr[j+1].

    Step 5: Increment j and go to Step 3.

    Step 6: Increment i and go to Step 2.

    Step 7: Output the sorted array.

    Working of Bubble Sort algorithm - Example




    Bubble Sort Code

                        
                            #include <stdio.h>
                            #include 
    
                                // A function to implement Bubble Sort
                                void bubbleSort(int arr[], int n) {
                                    int i, j, temp;
                                    for (i = 0; i < n - 1; i++) {
                                        // Last i elements are already sorted
                                        for (j = 0; j < n - i - 1; j++) {
                                            // Swap if the element found is greater than the next element
                                            if (arr[j] > arr[j + 1]) {
                                                temp = arr[j];
                                                arr[j] = arr[j + 1];
                                                arr[j + 1] = temp;
                                            }
                                        }
                                    }
                                }
                                
                                // Function to print an array
                                void printArray(int arr[], int size) {
                                    for (int i = 0; i < size; i++)
                                        printf("%d ", arr[i]);
                                    printf("\n");
                                }
                                
                                // Driver code
                                int main() {
                                    int n;
                                
                                    // Get the size of the array from the user
                                    printf("Enter the number of elements: ");
                                    scanf("%d", &n);
                                
                                    // Declare an array with a size based on user input
                                    int arr[n];
                                
                                    // Get the elements of the array from the user
                                    printf("Enter the elements of the array:\n");
                                    for (int i = 0; i < n; i++) {
                                        scanf("%d", &arr[i]);
                                    }
                                
                                    // Sort the array using Bubble Sort
                                    bubbleSort(arr, n);
                                
                                    // Print the sorted array
                                    printf("Sorted array: ");
                                    printArray(arr, n);
                                
                                    return 0;
                                }
                                
                                
                                
                        
                    
                        
                            #include <iostream>
                                using namespace std;
                                
                                void bubbleSort(int arr[], int n) {
                                    int i, j, temp;
                                    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]
                                                temp = arr[j];
                                                arr[j] = arr[j+1];
                                                arr[j+1] = temp;
                                            }
                                        }
                                    }
                                }
                                
                                void printArray(int arr[], int size) {
                                    for (int i = 0; i < size; i++)
                                        cout << arr[i] << " ";
                                    cout << endl;
                                }
                                
                                int main() {
                                    int arr[] = {64, 34, 25, 12, 22, 11, 90};
                                    int n = sizeof(arr)/sizeof(arr[0]);
                                    bubbleSort(arr, n);
                                    cout << "Sorted array: " << endl;
                                    printArray(arr, n);
                                    return 0;
                                }
                                
                        
                    
                        
                            public class BubbleSort {
    
                                static void bubbleSort(int[] arr) {
                                    int n = arr.length;
                                    int temp;
                                    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]
                                                temp = arr[j];
                                                arr[j] = arr[j+1];
                                                arr[j+1] = temp;
                                            }
                                        }
                                    }
                                }
                            
                                static void printArray(int[] arr) {
                                    for (int i : arr)
                                        System.out.print(i + " ");
                                    System.out.println();
                                }
                            
                                public static void main(String[] args) {
                                    int[] arr = {64, 34, 25, 12, 22, 11, 90};
                                    bubbleSort(arr);
                                    System.out.println("Sorted array:");
                                    printArray(arr);
                                }
                            }
                            
                        
                    
                        
                            def bubble_sort(arr):
                            n = len(arr)
                            for i in range(n-1):
                                for j in range(0, n-i-1):
                                    if arr[j] > arr[j+1]:
                                        # Swap arr[j] and arr[j+1]
                                        arr[j], arr[j+1] = arr[j+1], arr[j]
                        
                        def print_array(arr):
                            for i in arr:
                                print(i, end=' ')
                            print()
                        
                        if __name__ == "__main__":
                            arr = [64, 34, 25, 12, 22, 11, 90]
                            bubble_sort(arr)
                            print("Sorted array:")
                            print_array(arr)
                        
                        
                    

    Analysis of Bubble Sort

    Time Complexity

    Best Case: In the best case, the input array is already in sorted order, and the algorithm performs a minimum of n-1 comparisons. The best case complexity is O(n).

    Worst Case: In the worst case, the input array is in descending order, and the algorithm performs a maximum of n(n-1) comparisons. The algorithm performs n-1 iterations, and each iteration involves a maximum of n-1 comparisons. The worst-case and average-case complexity is O(n²). Space Complexity

    No additional space is required. The space complexity of insertion sort is O(1).

    Comparison of Insertion Sort and Bubble Sort