improved comments and algo description

This commit is contained in:
marsonya
2020-12-30 11:01:24 +05:30
parent a3e6c4c69e
commit 2acff23fdd

View File

@ -1,34 +1,34 @@
/** /**
* Bead sort (also known as Gravity sort) * Bead Sort, also known as Gravity sort, this algorithm was
* https://en.wikipedia.org/wiki/Bead_sort * inspired from natural phenomenons and was designed keeping in mind objects(or beads)
* falling under the influence of gravity.
* *
* Does counting sort of provided array according to * NOTE: It only works for arrays of positive integers.
* the digit represented by exp. *
* Only works for arrays of positive integers. * Wikipedia: https://en.wikipedia.org/wiki/Bead_sort
*/ */
/** /**
* Doctests * Doctests
* *
* > beadSort([-1, 5, 8, 4, 3, 19])
* ! RangeError: Sequence must be a list of positive integers!
* > beadSort([5, 4, 3, 2, 1]) * > beadSort([5, 4, 3, 2, 1])
* [1, 2, 3, 4, 5] * [1, 2, 3, 4, 5]
* > beadSort([7, 9, 4, 3, 5]) * > beadSort([7, 9, 4, 3, 5])
* [3, 4, 5, 7, 9] * [3, 4, 5, 7, 9]
* > beadSort([-1, 5, 8, 4, 3, 19])
* ! RangeError: Sequence must be a list of positive integers!
*/ */
function beadSort (sequence) { function beadSort (sequence) {
// first, let's check that our sequence consists /* Let's ensure our sequence has only Positive Integers */
// of positive integers
if (sequence.some((integer) => integer < 0)) { if (sequence.some((integer) => integer < 0)) {
throw RangeError('Sequence must be a list of positive integers!') throw RangeError('Sequence must be a list of Positive integers Only!')
} }
const sequenceLength = sequence.length const sequenceLength = sequence.length
const max = Math.max(...sequence) const max = Math.max(...sequence)
// set initial grid // Set initial Grid
const grid = sequence.map(number => { const grid = sequence.map(number => {
const maxArr = new Array(max) const maxArr = new Array(max)
@ -39,7 +39,7 @@ function beadSort (sequence) {
return maxArr return maxArr
}) })
// drop the beads! // Drop the Beads!
for (let col = 0; col < max; col++) { for (let col = 0; col < max; col++) {
let beadsCount = 0 let beadsCount = 0
@ -59,7 +59,7 @@ function beadSort (sequence) {
} }
} }
// and, finally, let's turn our bead rows into their respective numbers /* Finally, let's turn our Bead rows into their Respective Numbers */
const sortedSequence = grid.map((beadArray) => { const sortedSequence = grid.map((beadArray) => {
const beadsArray = beadArray.filter(bead => bead === '*') const beadsArray = beadArray.filter(bead => bead === '*')
@ -70,7 +70,7 @@ function beadSort (sequence) {
} }
/** /**
* Implementation of Cocktail Shaker Sort * Implementation of Bead Sort
*/ */
const array = [5, 4, 3, 2, 1] const array = [5, 4, 3, 2, 1]
// Before Sort // Before Sort