Skip to content

Commit 8daf45e

Browse files
authored
Merge pull request TheAlgorithms#719 from MrDoomy/feat/shuffle-algorithm
Added Fisher Yates Algorithm
2 parents fb763c4 + 0fea99d commit 8daf45e

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed

Sorts/FisherYatesShuffle.js

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
export const shuffle = (array) => {
2+
let maxLength = array.length
3+
let temp
4+
let idx
5+
6+
// While there remain elements to shuffle...
7+
while (maxLength) {
8+
// Pick a remaining element...
9+
idx = Math.floor(Math.random() * maxLength--)
10+
11+
// And swap it with the current element
12+
temp = array[maxLength]
13+
array[maxLength] = array[idx]
14+
array[idx] = temp
15+
}
16+
17+
return array
18+
}

Sorts/test/FisherYatesShuffle.test.js

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
import { shuffle } from '../FisherYatesShuffle'
2+
3+
describe('shuffle', () => {
4+
it('expects to have a new array with same size', () => {
5+
const fibonacci = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
6+
const mixedArray = shuffle(fibonacci)
7+
8+
expect(mixedArray).toHaveLength(fibonacci.length)
9+
})
10+
11+
it('expects to have a new array with same values', () => {
12+
const fibonacci = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
13+
const mixedArray = shuffle(fibonacci)
14+
15+
expect(mixedArray).toContain(0)
16+
expect(mixedArray).toContain(1)
17+
expect(mixedArray).toContain(2)
18+
expect(mixedArray).toContain(3)
19+
expect(mixedArray).toContain(5)
20+
expect(mixedArray).toContain(8)
21+
expect(mixedArray).toContain(13)
22+
expect(mixedArray).toContain(21)
23+
expect(mixedArray).toContain(34)
24+
expect(mixedArray).toContain(55)
25+
expect(mixedArray).toContain(89)
26+
})
27+
})

0 commit comments

Comments
 (0)