MCPcopy Create free account
hub / github.com/TheAlgorithms/JavaScript / selectionSort

Function selectionSort

Sorts/SelectionSort.js:11–37  ·  view source on GitHub ↗
(list)

Source from the content-addressed store, hash-verified

9 */
10
11export const selectionSort = (list) => {
12 if (!Array.isArray(list)) {
13 throw new TypeError('Given input is not an array')
14 }
15 const items = [...list] // We don't want to modify the original array
16 const length = items.length
17 for (let i = 0; i < length - 1; i++) {
18 if (typeof items[i] !== 'number') {
19 throw new TypeError('One of the items in your array is not a number')
20 }
21 // Number of passes
22 let min = i // min holds the current minimum number position for each pass; i holds the Initial min number
23 for (let j = i + 1; j < length; j++) {
24 // Note that j = i + 1 as we only need to go through unsorted array
25 if (items[j] < items[min]) {
26 // Compare the numbers
27 min = j // Change the current min number position if a smaller num is found
28 }
29 }
30 if (min !== i) {
31 // After each pass, if the current min num != initial min num, exchange the position.
32 // Swap the numbers
33 ;[items[i], items[min]] = [items[min], items[i]]
34 }
35 }
36 return items
37}

Callers 1

Calls

no outgoing calls

Tested by

no test coverage detected