-
Notifications
You must be signed in to change notification settings - Fork 3
/
selection-sort.js
30 lines (29 loc) · 940 Bytes
/
selection-sort.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/*
* The Selection sort algorithm divides the input list into two parts: the
sublist of items already sorted and the sublist of items remaining to be
sorted that occupy the rest of the list. Initially, the sorted sublist is
empty and the unsorted sublist is the entire input list. The algorithm
proceeds by finding the smallest element in the unsorted sublist, exchanging
it with the leftmost unsorted element, and moving the sublist boundaries one
element to the right
*
* MORE INFO: https://en.wikipedia.org/wiki/Selection_sort
*/
function swap(arr, currentIndex, minIndex) {
const temp = arr[currentIndex];
arr[currentIndex] = arr[minIndex];
arr[minIndex] = temp;
}
export function selectionSort(arr, n = arr.length) {
let min;
for (let i = 0; i < n; i++) {
min = i;
for (let j = i; j < n; j++) {
if (arr[j] < arr[min]) {
min = j;
}
}
swap(arr, i, min);
}
return arr;
}