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 1231be9

Browse files
committed
implemented selection sort
1 parent 40da709 commit 1231be9

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

‎src/sorting/bubble.js‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
const bubbleSort = (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+
for (let j = 0; j < (result.length - i - 1); j += 1) {
9+
if (result[j] > result[j + 1]) {
10+
[result[j], result[j + 1]] = [result[j + 1], result[j]];
11+
}
12+
}
13+
}
14+
15+
return result;
16+
};
17+
18+
module.exports = bubbleSort;

‎tests/sorting/bubble.test.js‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
const bubbleSort = require('../../src/sorting/bubble');
2+
3+
describe('bubble sort unit test:', () => {
4+
it('Test#1 simple', async () => {
5+
const want = [2, 3, 5, 6, 7, 9];
6+
const got = bubbleSort([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 = bubbleSort([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 = bubbleSort([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 によって変換されたページ (->オリジナル) /