11/**
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.
45 *
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
89 */
910
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+ */
1621
1722function 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 */
2024 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 !' )
2226 }
2327
2428 const sequenceLength = sequence . length
2529 const max = Math . max ( ...sequence )
2630
27- // set initial grid
31+ // Set initial Grid
2832 const grid = sequence . map ( number => {
2933 const maxArr = new Array ( max )
3034
@@ -35,7 +39,7 @@ function beadSort (sequence) {
3539 return maxArr
3640 } )
3741
38- // drop the beads !
42+ // Drop the Beads !
3943 for ( let col = 0 ; col < max ; col ++ ) {
4044 let beadsCount = 0
4145
@@ -55,7 +59,7 @@ function beadSort (sequence) {
5559 }
5660 }
5761
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 */
5963 const sortedSequence = grid . map ( ( beadArray ) => {
6064 const beadsArray = beadArray . filter ( bead => bead === '*' )
6165
@@ -65,5 +69,14 @@ function beadSort (sequence) {
6569 return sortedSequence
6670}
6771
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