Median-Cut Algorithm
Median-cut divides the RGB color space into regions by repeatedly splitting along the axis with the greatest range. Each final region produces one palette color, weighted by the pixel count it represents.
// Median-cut in 3 steps:
// 1. Find the color channel with largest spread
const axis = maxSpread(pixels); // R, G, or B
// 2. Sort pixels along that axis
pixels.sort((a, b) => a[axis] - b[axis]);
// 3. Split at the median
const mid = pixels.length / 2;
recurse(pixels.slice(0, mid)); // → left bucket
recurse(pixels.slice(mid)); // → right bucket