DEV Community

loading...

Discussion on: Daily Challenge #308 - Wave Sort

Collapse
willsmart profile image
willsmart

A little one version in pretty damn cryptic but possibly speedy JS.

const waveSort = array => array
    .sort((a, b) => b - a)
    .map((_, i, arr) => arr[(i & 1) * ((arr.length + 1) >> 1) + (i >> 1)]);
Enter fullscreen mode Exit fullscreen mode

The call to sort sorts the array by descending value.

The call to map performs a one-to-one mapping of elements:

  • The (i & 1) * ((arr.length + 1) >> 1) alternates between the first half of the array and the second half
  • The 'i >> 1` adds an index that increments every second element

Because the elements in the first half are all greater than or equal to the elements in the first half, it's a wave sort.

Tested in the kata