forked from keshavsingh4522/hacktoberfest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
selectionSorting.js
28 lines (26 loc) 路 799 Bytes
/
selectionSorting.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
/// function that sorts an array using selection sort
const selectionSort = (inputArr) => {
for (let i = 0; i < inputArr.length - 1; i++) {
let foundMinimum = false;
let minIndex = i;
for (let j = i + 1; j < inputArr.length; j++) {
if (inputArr[j] < inputArr[minIndex]) {
foundMinimum = true;
minIndex = j;
}
}
if (foundMinimum) {
inputArr = swap(inputArr, i, minIndex);
}
}
return inputArr;
};
// efficient swap function using bitwise XOR.
const swap = (inputArr, i, minIndex) => {
inputArr[i] = inputArr[i] ^ inputArr[minIndex];
inputArr[minIndex] = inputArr[i] ^ inputArr[minIndex];
inputArr[i] = inputArr[i] ^ inputArr[minIndex];
return inputArr;
};
//test function
console.log(selectionSort([90, 12, 58, -2, -5, -30]));