> For the complete documentation index, see [llms.txt](https://liuyang89116.gitbook.io/my-leetcode-book/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://liuyang89116.gitbook.io/my-leetcode-book/basics_of_sorting/selection_sort.md).

# Selection Sort

## 思路

不断地选择剩余元素中的最小者。

* 找到数组中最小元素并将其和数组第一个元素交换位置。
* 在剩下的元素中找到最小元素并将其与数组第二个元素交换，直至整个数组排序。

![](/files/-Lpv9zpYxma2VOPBKQNK)

## 复杂度分析

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

```java
package selectionSort;

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

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

    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
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, and the optional `goal` query parameter:

```
GET https://liuyang89116.gitbook.io/my-leetcode-book/basics_of_sorting/selection_sort.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
