Skip to content

Commit f888434

Browse files
Merge pull request akshitagit#33 from VolatianaYuliana/selection-sort
create selection sort
2 parents a492618 + 9f47a50 commit f888434

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

Sorts/SelectionSort.js

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
export default SelectionSort = function (arr) {
2+
let n = arr.length;
3+
4+
for (let i = 0; i < n; i++) {
5+
// Set the minimum to this position.
6+
min_index = i;
7+
8+
// Looking for a smaller number in the unsorted subarray.
9+
for (let j = i + 1; j < n; j++) {
10+
// If find one, set the minimum to this position.
11+
if (arr[j] < arr[min_index]) {
12+
min_index = j;
13+
}
14+
}
15+
16+
// If the current minimum index is not the minimum index you started with, swap the elements.
17+
if (min_index != i) {
18+
let temp = arr[i];
19+
arr[i] = arr[min_index];
20+
arr[min_index] = temp;
21+
}
22+
}
23+
return arr;
24+
};

0 commit comments

Comments
 (0)