# Bubble Sort

## 思路

核心：**冒泡**，持续比较相邻元素，大的挪到后面，因此大的会逐步往后挪，故称之为冒泡。

![](/files/-Lpv9zUt00ycq71_IrYw)

## 复杂度分析

**Best**: $$\Omega (n)$$\
**Worst**: $$O(n^2)$$\
**Average**: $$\Theta(n^2)$$

```java
package bubbleSort;

public class BubbleSort {
    public static void main(String[] args) {
        int[] unsortedArr = new int[] { 6, 5, 3, 1, 8, 7, 2, 4 };
        bubbleSort(unsortedArr);
        System.out.println("After Sort: ");
        printArr(unsortedArr);
    }

    private static void bubbleSort(int[] arr) {
        int len = arr.length;
        for (int i = 0; i < len; i++) {
            printArr(arr);
            System.out.println();
            for (int j = 1; j < len - i; j++) {
                if (arr[j - 1] > arr[j]) {
                    swap(arr, j - 1, j);
                }
            }
        }
    }

    private static void swap(int[] arr, int i, int j) {
        int tmp = arr[i];
        arr[i] = arr[j];
        arr[j] = tmp;
    }

    private static void printArr(int[] arr) {
        for (Integer num : arr) {
            System.out.print(num + " ");
        }
    }
}
```


---

# 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://liuyang89116.gitbook.io/my-leetcode-book/basics_of_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.
