1
1
/**
2
- * Bead sort (also known as Gravity sort)
3
- * https://en.wikipedia.org/wiki/Bead_sort
2
+ * Bead Sort, also known as Gravity sort, this algorithm was
3
+ * inspired from natural phenomenons and was designed keeping in mind objects(or beads)
4
+ * falling under the influence of gravity.
4
5
*
5
- * Does counting sort of provided array according to
6
- * the digit represented by exp.
7
- * Only works for arrays of positive integers.
6
+ * NOTE: It only works for arrays of positive integers.
7
+ *
8
+ * Wikipedia: https://en.wikipedia.org/wiki/Bead_sort
8
9
*/
9
10
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]
11
+ /**
12
+ * Doctests
13
+ *
14
+ * > beadSort([5, 4, 3, 2, 1])
15
+ * [1, 2, 3, 4, 5]
16
+ * > beadSort([7, 9, 4, 3, 5])
17
+ * [3, 4, 5, 7, 9]
18
+ * > beadSort([-1, 5, 8, 4, 3, 19])
19
+ * ! RangeError: Sequence must be a list of positive integers!
20
+ */
16
21
17
22
function beadSort ( sequence ) {
18
- // first, let's check that our sequence consists
19
- // of positive integers
23
+ /* Let's ensure our sequence has only Positive Integers */
20
24
if ( sequence . some ( ( integer ) => integer < 0 ) ) {
21
- throw RangeError ( 'Sequence must be a list of positive integers!' )
25
+ throw RangeError ( 'Sequence must be a list of Positive integers Only !' )
22
26
}
23
27
24
28
const sequenceLength = sequence . length
25
29
const max = Math . max ( ...sequence )
26
30
27
- // set initial grid
31
+ // Set initial Grid
28
32
const grid = sequence . map ( number => {
29
33
const maxArr = new Array ( max )
30
34
@@ -35,7 +39,7 @@ function beadSort (sequence) {
35
39
return maxArr
36
40
} )
37
41
38
- // drop the beads !
42
+ // Drop the Beads !
39
43
for ( let col = 0 ; col < max ; col ++ ) {
40
44
let beadsCount = 0
41
45
@@ -55,7 +59,7 @@ function beadSort (sequence) {
55
59
}
56
60
}
57
61
58
- // and, finally, let's turn our bead rows into their respective numbers
62
+ /* Finally, let's turn our Bead rows into their Respective Numbers */
59
63
const sortedSequence = grid . map ( ( beadArray ) => {
60
64
const beadsArray = beadArray . filter ( bead => bead === '*' )
61
65
@@ -65,5 +69,14 @@ function beadSort (sequence) {
65
69
return sortedSequence
66
70
}
67
71
68
- // implementation
69
- console . log ( beadSort ( [ 5 , 4 , 3 , 2 , 1 ] ) )
72
+ /**
73
+ * Implementation of Bead Sort
74
+ */
75
+ const array = [ 5 , 4 , 3 , 2 , 1 ]
76
+ // Before Sort
77
+ console . log ( '\n- Before Sort | Implementation of Bead Sort -' )
78
+ console . log ( array )
79
+ // After Sort
80
+ console . log ( '- After Sort | Implementation of Bead Sort -' )
81
+ console . log ( beadSort ( array ) )
82
+ console . log ( '\n' )
0 commit comments