forked from TheAlgorithms/JavaScript
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBeadSort.js
More file actions
Latest commit
56 lines (48 loc) · 1.4 KB
/
Copy pathBeadSort.js
File metadata and controls
56 lines (48 loc) · 1.4 KB
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
/**
* Bead Sort, also known as Gravity sort.
*
* This algorithm was inspired from natural phenomena and was designed keeping in mind objects (or beads) falling under
* the influence of gravity.
*
* NOTE: It only works for arrays of positive integers.
*
* Wikipedia: https://en.wikipedia.org/wiki/Bead_sort
*/
exportfunctionbeadSort(sequence){
/* Let's ensure our sequence has only Positive Integers */
if(sequence.some((integer)=>integer<0)){
throwRangeError('Sequence must be a list of Positive integers Only!')
}
constsequenceLength=sequence.length
constmax=Math.max(...sequence)
// Set initial Grid
constgrid=sequence.map((number)=>{
constmaxArr=newArray(max)
for(leti=0;i<number;i++){
maxArr[i]='*'
}
returnmaxArr
})
// Drop the Beads!
for(letcol=0;col<max;col++){
letbeadsCount=0
for(letrow=0;row<sequenceLength;row++){
if(grid[row][col]==='*'){
beadsCount++
}
}
for(letrow=sequenceLength-1;row>-1;row--){
if(beadsCount){
grid[row][col]='*'
beadsCount--
}else{
grid[row][col]=undefined
}
}
}
/* Finally, let's turn our Bead rows into their Respective Numbers */
returngrid.map((beadArray)=>{
constbeadsArray=beadArray.filter((bead)=>bead==='*')
returnbeadsArray.length
})
}