Data Structures & AlgorithmsHardGATE CS · DSA

Shell sort with gap sequence 4, 2, 1 (gapped insertion sort for each gap). What is the array after the gap-4 pass only?

Shell sort with gap sequence 4, 2, 1 (gapped insertion sort for each gap). What is the array after the gap-4 pass only?
a = [20, 16, 6, 28, 21, 3, 15, 38, 1]
gap = 4
for i in range(gap, len(a)):
    x, j = a[i], i
    while j >= gap and a[j - gap] > x:
        a[j] = a[j - gap]; j -= gap
    a[j] = x
print(a)
  1. A. [1, 3, 28, 6, 20, 16, 15, 38, 21]
  2. B. [1, 3, 6, 28, 20, 15, 16, 38, 21]
  3. C. [20, 3, 6, 28, 1, 16, 15, 38, 21]
  4. D. [1, 3, 6, 28, 20, 16, 15, 38, 21]

Correct answer: D. [1, 3, 6, 28, 20, 16, 15, 38, 21]

Elements 4 apart form sub-lists that are each insertion-sorted; with 9 elements, index 0, 4, 8 form one chain, so an element can move two gaps. Output: [1, 3, 6, 28, 20, 16, 15, 38, 21].

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic