Skip to the code
cf.
+25 XP

#209 Shell Sort Gap Snapshots

medium

A sorting tutorial shows Shell sort one gap at a time. The gaps start at Math.floor(n / 2) and halve (rounding down) until they reach 1. For each gap, it runs a gapped insertion sort: for i from gap to n - 1, lift out nums[i] and shift earlier items in the same gap group (i - gap, i - 2 × gap, ...) that are strictly bigger forward by gap, then drop the lifted item into the opening.

Write shellPasses(nums) that returns an array of snapshots, a copy of the list after each gap's pass. A list with fewer than 2 items has no gaps, so return [].

Example 1

Input: nums = [23,12,1,8,34,54,2,3]
Output: [[23,12,1,3,34,54,2,8],[1,3,2,8,23,12,34,54],[1,2,3,8,12,23,34,54]]

Gaps 4, 2, and 1. With gap 4 only 8 and 3 are out of order.

Example 2

Input: nums = [2,1]
Output: [[1,2]]

Only gap 1, a plain insertion sort.

Constraints

  • 0 <= nums.length <= 200
  • -1000 <= nums[i] <= 1000
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).