# Selection sort

## Definition

Selection sort is an in-place comparison sorting algorithm. It divides the input array into a sorted and an unsorted subarray. It then repeatedly finds the minimum element in the unsorted subarray and swaps it with the leftmost element in the unsorted subarray, moving the subarray boundaries one element to the right.

## Implementation

```const selectionSort = arr => {
const a = [...arr];
for (let i = 0; i < a.length; i++) {
const min = a
.slice(i + 1)
.reduce((acc, val, j) => (val < a[acc] ? j + i + 1 : acc), i);
if (min !== i) [a[i], a[min]] = [a[min], a[i]];
}
return a;
};

selectionSort([5, 1, 4, 2, 3]); // [1, 2, 3, 4, 5]```

## Complexity

The algorithm has an average time complexity of `O(n^2)`, where `n` is the size of the input array.

## More like this

• Collection · 108 snippets

### JavaScript Arrays

Master array manipulation in JavaScript with this ES6 snippet collection.

• JavaScript ·

### Heap sort

Sort an array of numbers, using the heapsort algorithm.

• JavaScript ·

### Bucket sort

Sort an array of numbers, using the bucket sort algorithm.

• JavaScript ·

### Quick sort

Sort an array of numbers, using the quicksort algorithm.

Start typing a keyphrase to see matching snippets.