Gravity (Bead) Sort

Simulates beads falling under gravity on an abacus. Each value is represented as a row of beads that drop into place.

Best O(n) Avg O(S) Worst O(S) Space O(n*m) Stable No In-place No Distribution

How it works

Simulates beads falling under gravity on an abacus. Each value is represented as a row of beads that drop into place.

Implementation

function gravitySort(arr) {
  const max = Math.max(...arr);
  const grid = Array.from({length: arr.length},
    () => new Array(max).fill(0));
  for (let i = 0; i < arr.length; i++)
    for (let j = 0; j < arr[i]; j++) grid[i][j] = 1;
  for (let col = 0; col < max; col++) {
    let beads = 0;
    for (let row = 0; row < arr.length; row++) {
      beads += grid[row][col]; grid[row][col] = 0;
    }
    for (let row = arr.length-1; row >= arr.length-beads; row--)
      grid[row][col] = 1;
  }
  for (let i = 0; i < arr.length; i++)
    arr[i] = grid[i].reduce((a,v) => a+v, 0);
}