> For the complete documentation index, see [llms.txt](https://zedive.gitbook.io/project-l/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://zedive.gitbook.io/project-l/part-2/divide_and_conquer/sorting/bubble-sort.md).

# Bubble Sort

## Question ([LC.463](http://www.lintcode.com/en/problem/sort-integers/))

> Given an integer array, sort it in ascending order. Use selection sort, bubble sort, insertion sort or any O(n^2) algorithm.

## Key Idea

Each iteration the largest element will be bubbled to the top.

## Debug&#x20;

Why this implementation is wrong? hint: what do you know for sure after each iteration in the outer loop?&#x20;

```python
def sortIntegers(self, A: List[int]) -> None:
    """
    Bubbling up the current element to the end of the list is also an option.
    """
    
    n = len(A)
    for i in range(n):
        for j in range(i, n-1):
            if A[j] > A[j+1]:
                temp = A[j]
                A[j] = A[j+1]
                A[j+1] = temp
```

## Code

```java
public void bubbleSort(int[] arr) {
    // each outer loop guarantees the largest element 
    // is bubbled to the right place
    for (int i = 0; i < arr.length - 1; i++)
        for (int j = 1; j < arr.length - i; j++)
            if (arr[j-1] > arr[j]) swap(arr, j-1, j);
}

private void swap(int[] arr, int index1, int index2) {
    int temp = arr[index1];
    arr[index1] = arr[index2];
    arr[index2] = temp;
}
```

```go
func sortIntegers (A *[]int)  {    
    arr := *A
    
    if arr == nil || len(arr) == 0 {
        return
    }
    
    // for each element swap the smallest value to the front 
    
    for i := 0; i < len(arr); i++ {
        for j := i; j > 0; j-- {
            if arr[j-1] > arr[j] {
                swap(A, j-1, j)
            }
        }
    }
}

func swap (A *[]int, i, j int) {
    arr := *A 
    temp := arr[i]
    arr[i] = arr[j]
    arr[j] = temp
}
```

```python
def bubbleSort(A: List[int]) -> None:
    """
    Bubbling the largest element to the end of the list 
    """
    
    n = len(A)
    for i in range(n):
        for j in range(n-i-1):
            if A[j] > A[j+1]:
                swap(A, j, j+1)


def swap(A: List[Any], i: int, j: int) -> None:
    temp = A[i]
    A[i] = A[j]
    A[j] = temp 
```

## Time & Space Complexity

Bubble sort has quite a few nice properties. Since it only involves swapping elements, it is in-place. The finishing order is also stable. The time complexity can be calculated with a simple summation $$\sum\limits\_{i=0}^{n-1} i = n^2$$.

## Optimization

We can add a flag to check if the inner loop has 0 swaps. That will improve the best case to O(n).


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## 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://zedive.gitbook.io/project-l/part-2/divide_and_conquer/sorting/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.
