Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 40da709

Browse files
committed
implemented selection sort
1 parent b1a37f8 commit 40da709

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed

‎src/sorting/selection.js‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
const selectionSort = (arr) => {
2+
// No need to sort the array if the array only has one element or empty
3+
if (arr.length < 2) return arr;
4+
5+
const result = arr.slice(0);
6+
7+
for (let i = 0; i < result.length; i += 1) {
8+
let minIndex = i;
9+
for (let j = i + 1; j < result.length; j += 1) {
10+
if (result[j] < result[minIndex]) {
11+
minIndex = j;
12+
}
13+
}
14+
15+
[result[i], result[minIndex]] = [result[minIndex], result[i]];
16+
}
17+
18+
return result;
19+
};
20+
21+
module.exports = selectionSort;

‎tests/sorting/selection.test.js‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
const selectionSort = require('../../src/sorting/selection');
2+
3+
describe('selection sort unit test:', () => {
4+
it('Test#1 simple', async () => {
5+
const want = [2, 3, 5, 6, 7, 9];
6+
const got = selectionSort([5, 3, 7, 6, 2, 9]);
7+
expect(got).toEqual(want);
8+
});
9+
10+
it('Test#2 duplicate value', async () => {
11+
const want = [2, 3, 5, 5, 6, 7, 7, 9];
12+
const got = selectionSort([5, 3, 7, 6, 2, 9, 7, 5]);
13+
expect(got).toEqual(want);
14+
});
15+
16+
it('Test#3 with negative value', async () => {
17+
const want = [-7, -7, -3, 6, 17, 34, 42, 50, 52, 83, 87, 89, 96];
18+
const got = selectionSort([83, 52, 89, 42, 6, 87, 50, 17, 34, 96, -7, -3, -7]);
19+
expect(got).toEqual(want);
20+
});
21+
});

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /