> For the complete documentation index, see [llms.txt](https://tanias-workspace.gitbook.io/tanias-little-corner/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://tanias-workspace.gitbook.io/tanias-little-corner/algorithms/selection-sort.md).

# Selection Sort

Selection Sort repeatedly selects the smallest element from the unsorted portion and moves it to the beginning of the array.

**Steps**:

1. Start with the first element.
2. Find the smallest element in the remaining unsorted portion.
3. Swap it with the current element.
4. Move to the next element and repeat.

<figure><img src="/files/529qGILozC3Md2dXmj7s" alt="" width="375"><figcaption></figcaption></figure>

```cpp
#include <vector>
#include <iostream>

void selectionSort(std::vector<int> &arr) {
    int n = arr.size();
    for (int i = 0; i < n - 1; i++) {
        int minIndex = i;
        for (int j = i + 1; j < n; j++) {
            if (arr[j] < arr[minIndex]) {
                minIndex = j;
            }
        }
        std::swap(arr[i], arr[minIndex]);
    }
}

int main() {
    std::vector<int> arr = {64, 34, 25, 12, 22, 11, 90};
    selectionSort(arr);
    for (int num : arr) std::cout << num << " ";
    return 0;
}

```

**Selection Sort**: Simple and has consistent performance but still O(n^2).
