Skip to the code
cf.
+10 XP

#210 One Gapped Insertion Pass

easy

Shell sort is built from gapped insertion passes. One pass with gap gap insertion-sorts each group of items that are gap apart: positions 0, gap, 2 × gap, ..., then 1, 1 + gap, ..., and so on, each group on its own.

Write gappedPass(nums, gap) that returns a new array after one such pass. Items in different groups never move relative to each other's positions.

Example 1

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

The groups are (23, 34), (12, 54), (1, 2), and (8, 3). Only the last group is out of order.

Example 2

Input: nums = [5,4,3,2,1], gap = 1
Output: [1,2,3,4,5]

Gap 1 is a normal insertion sort.

Constraints

  • 0 <= nums.length <= 1000
  • 1 <= gap <= 1000
  • -10^6 <= nums[i] <= 10^6
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).