-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathselection-sort.js
34 lines (30 loc) · 1015 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
31
32
33
34
// implementing selection sort;
function selectionSortByAscending(nums) {
if (!Array.isArray(arr)) throw new Error("argument must be array");
for (let i = 0; i < nums.length; i++) {
let minIndex = i;
for (let j = i + 1; j < nums.length; j++) {
if (nums[minIndex] > nums[j]) {
minIndex = j;
}
}
[nums[minIndex], nums[i]] = [nums[i], nums[minIndex]]; // swap operation
}
return nums;
}
function selectionSortByDescending(nums) {
if (!Array.isArray(arr)) throw new Error("argument must be array");
for (let i = 0; i < nums.length; i++) {
let minIndex = i;
for (let j = i + 1; j < nums.length; j++) {
if (nums[minIndex] < nums[j]) {
minIndex = j;
}
}
[nums[minIndex], nums[i]] = [nums[i], nums[minIndex]]; // swap operation
}
return nums;
}
// testing;
console.log(selectionSortByAscending([9, 5, 1, 7, 3, 2, 6, 5, 8]));
console.log(selectionSortByDescending([9, 5, 1, 7, 3, 2, 6, 5, 8]));