Repair an overwrite error

A programmer writes the following faulty Python code for one ascending insertion-sort pass. The entries before index i are already sorted, and key has been saved before the loop.


Python
key = a[i]
j = i - 1
while j >= 0 and a[j] > key:
    j = j - 1
    a[j + 1] = a[j]
a[j] = key


Complete the repair instructions. Use only left or right for directions and before or after for timing. Keep the loop condition unchanged.


Each shift copies an earlier value one position to the . Within the loop, decrement j copying the value selected by the current j. When the loop finishes, write the saved key immediately to the of index j.

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

More Insertion Sort Questions: