# Bubble Sort

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`).

{% hint style="success" %}
At every ith round, we deliver its ith largest element at the right place.
{% endhint %}

## `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:`** <https://www.codingninjas.com/studio/problems/bubble-sort_980524>

**`Notes:`** <https://drive.google.com/file/d/1DScaSvG0TzAy2b9MF9CcEtzoOxvai3MY/view>

```cpp
#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;
    }
}
```

&#x20; **Solved by Recursion**

```cpp
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 <mark style="color:blue;">`Already shorted O(n).`</mark>

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.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://dsa-cpp.gitbook.io/nafees/sorting-algorithms/bubble-sort.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
