< Nafees />
github
  • Assignments - DSA
  • Long Integer Operations
  • OOP
    • Introduction
    • Implementation
  • Sorting Algorithms
    • Selection Sort
    • Bubble Sort
    • Insertion Sort
    • Shell Sort
    • Shuffle
    • Merge Sort
    • Convex Hull
    • Quick sort
    • System Sort
    • Heap-Sort
  • Binary Search
  • Binary Search By Recursion
  • Two-Pointer
  • String
  • LeetCode 75
    • Array/String
    • Hash Map
    • BST
    • Binary Search
  • Top Interview 150
    • Linked-List
  • Leetcode Programming Skill
    • Math
  • Leetcode 75
  • 🤡Leet Code Extra
  • Arrays
    • 1-D Array
    • 2-D Arrays
  • 👨‍🍳Basic Math - Codechef
  • ☠️Recursion
  • 😁Public Member Functions
    • Strings Functions
  • 👾Linked List
    • What's Linked List & Implementation?
      • Singly Linked List
      • Doubly Linked List
    • Problems
  • 📚Stack
    • What's Stack & Implementation?
      • Stack Using Array
      • Stack using LL
    • Problems
  • 🏧Queue
    • What's Queue & Implementation?
      • Simple Queue
      • Queue using LL
      • Circular Queue
      • Deque using Linked List
      • STL Deque
    • Problems
  • 🏧Priority Queue
    • What's Priority Queue & Implementation
      • OrderedArrayMaxPQ.Java
      • Maximum-Oriented PQ using Binary Heap
      • Minimum-Oriented PQ using Binary Heap
    • Problems
  • 🗓️Hash Table
    • What's Hash Table & Implementation
      • ST - Seperate Chaining
      • ST - Linear Probing
    • Problems
  • 🎴Symbol Table
    • What's Symbol Table and implementation
      • ST Using Binary search (ordered array)
      • ST Using Binary Search Tree
      • ST Using Left-Leaning Red-Black Tree
      • ST Using Hash Table
    • Problems
  • 🔗Union-Find (Dynamic Connectivity problem)
    • What is a Union Find Data Structure?
    • Implementation
  • 🎋Binary Tree
    • What's Binary Tree & Implementation?
      • Traversal
      • Red-Black BST
  • 🌴Trie
    • What's Trie & Implementation?
    • Problems
  • 😎Project
    • Expression Evaluation
Powered by GitBook
On this page

Was this helpful?

  1. Sorting Algorithms

Bubble Sort

Bubble sort is a simple sorting algorithm that works by repeatedly comparing adjacent elements in an array and swapping them if they are in the wrong order.

PreviousSelection SortNextInsertion Sort

Last updated 1 year ago

Was this helpful?

The algorithm starts at the beginning of the array and compares the first two elements. If the first element is greater than the second element, the two elements are swapped. The algorithm then moves on to the next two elements and repeats the process. This continues until the end of the array is reached(j < n - i).

At every ith round, we deliver its ith largest element at the right place.

Use Case

In general, bubble sort should only be used when speed is not a major concern or when the array is already mostly sorted.

Question statement:

Notes:

#include <bits/stdc++.h> 
void BubbleSort(vector<int>& arr, int n){
    for(int i = 1; i < n; i++){
        // for Round i to n-1
        bool isSorted = true; // condition for if the given array already sorted

        for(int j = 0; j < n-i; j++){
            // process elements till n-i index

            if(arr[j] > arr[j+1]){ 
                swap(arr[j], arr[j+1]);
                isSorted = false; // not sorted
            }
        }
        if(isSorted)
            break;
    }
}

Solved by Recursion

void bubbleSort(vector<int>& arr, int n){
    if(n == 0 || n == 1)
        return ;
    for(int i = 0; i < n-1; i++){
        if(arr[i] > arr[i+1])
            swap(arr[i], arr[i+1]);
    }
    bubbleSort(arr, n-1);
}

Code Explanation:

  1. The for loop iterates from 1 to n-1 (1<n), where n is the number of elements in the array.

  2. The bool variable isSorted is initialized to true. This variable will be used to track whether the array is already sorted.

  3. The for loop iterates from 0 to n-i-1 (O<n-i), where i is the current iteration of the outer loop.

  4. The if statement checks if the current element is greater than the next element. If it is, the two elements are swapped.

  5. The isSorted variable is set to false if the array is not sorted. This will cause the outer loop to continue iterating.

  6. The outer if statement checks if the array is sorted. If it is, the algorithm terminates.

Best Case: If any case comes where no. of swaps doesn't exit so, move out by breaking no need to do anything. Its Already shorted O(n).

The bubble sort algorithm is a very simple algorithm to understand and implement. However, it is also a very inefficient algorithm, with a worst-case time complexity of O(n^2). This means that the time it takes to sort an array using bubble sort grows quadratically with the size of the array. For this reason, bubble sort is not a good choice for sorting large arrays.

However, bubble sort can be a good choice for sorting small arrays or for sorting arrays that are already mostly sorted. In these cases, the inefficiency of bubble sort may not be a major concern.

https://www.codingninjas.com/studio/problems/bubble-sort_980524
https://drive.google.com/file/d/1DScaSvG0TzAy2b9MF9CcEtzoOxvai3MY/view
Page cover image