|
| 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