Skip to content

Commit 554abf7

Browse files
authored
Add Bead Sort (aka Gravity Sort) Algorithm (#388)
* add BeadSort.js * add BeadSort to directory * run npx standard & fix linter issues * add bead sort implementation w/ console.log()
1 parent a67a2cb commit 554abf7

File tree

2 files changed

+70
-0
lines changed

2 files changed

+70
-0
lines changed

DIRECTORY.md

+1
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,7 @@
141141
* [StringSearch](https://github.com/TheAlgorithms/Javascript/blob/master/Search/StringSearch.js)
142142

143143
## Sorts
144+
* [BeadSort](https://github.com/TheAlgorithms/Javascript/blob/master/Sorts/BeadSort.js)
144145
* [BogoSort](https://github.com/TheAlgorithms/Javascript/blob/master/Sorts/BogoSort.js)
145146
* [BubbleSort](https://github.com/TheAlgorithms/Javascript/blob/master/Sorts/BubbleSort.js)
146147
* [BucketSort](https://github.com/TheAlgorithms/Javascript/blob/master/Sorts/BucketSort.js)

Sorts/BeadSort.js

+69
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
/**
2+
* Bead sort (also known as Gravity sort)
3+
* https://en.wikipedia.org/wiki/Bead_sort
4+
*
5+
* Does counting sort of provided array according to
6+
* the digit represented by exp.
7+
* Only works for arrays of positive integers.
8+
*/
9+
10+
// > beadSort([-1, 5, 8, 4, 3, 19])
11+
// ! RangeError: Sequence must be a list of positive integers!
12+
// > beadSort([5, 4, 3, 2, 1])
13+
// [1, 2, 3, 4, 5]
14+
// > beadSort([7, 9, 4, 3, 5])
15+
// [3, 4, 5, 7, 9]
16+
17+
function beadSort (sequence) {
18+
// first, let's check that our sequence consists
19+
// of positive integers
20+
if (sequence.some((integer) => integer < 0)) {
21+
throw RangeError('Sequence must be a list of positive integers!')
22+
}
23+
24+
const sequenceLength = sequence.length
25+
const max = Math.max(...sequence)
26+
27+
// set initial grid
28+
const grid = sequence.map(number => {
29+
const maxArr = new Array(max)
30+
31+
for (let i = 0; i < number; i++) {
32+
maxArr[i] = '*'
33+
}
34+
35+
return maxArr
36+
})
37+
38+
// drop the beads!
39+
for (let col = 0; col < max; col++) {
40+
let beadsCount = 0
41+
42+
for (let row = 0; row < sequenceLength; row++) {
43+
if (grid[row][col] === '*') {
44+
beadsCount++
45+
}
46+
}
47+
48+
for (let row = sequenceLength - 1; row > -1; row--) {
49+
if (beadsCount) {
50+
grid[row][col] = '*'
51+
beadsCount--
52+
} else {
53+
grid[row][col] = undefined
54+
}
55+
}
56+
}
57+
58+
// and, finally, let's turn our bead rows into their respective numbers
59+
const sortedSequence = grid.map((beadArray) => {
60+
const beadsArray = beadArray.filter(bead => bead === '*')
61+
62+
return beadsArray.length
63+
})
64+
65+
return sortedSequence
66+
}
67+
68+
// implementation
69+
console.log(beadSort([5, 4, 3, 2, 1]))

0 commit comments

Comments
 (0)