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.
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.
Unlock full course notes by signing up
Comparisons include unsuccessful tests
A program sorts response times [2, 4, 6, 8, 10, 1], measured in milliseconds, using this insertion-sort code:
How many times is a[j] > key evaluated during the complete sort? Count both true and false evaluations of that expression, but exclude evaluations of j >= 0. Report the number of comparisons as an exact whole number.
Equal scores and stable ordering
An event system stores records in arrival order. It sorts them by ascending score using the code below. The expression .score reads a record's score, and assignments move the entire record. Equal scores are possible.
Select all true statements about keeping the strict comparison or changing only > to >=.
Resume from a verified prefix
A scheduler has six job durations already sorted in ascending order. It appends three new jobs, giving the array [10, 20, 30, 40, 50, 60, 15, 35, 55], with every value measured in milliseconds.
A continuation runs insertion sort beginning at index 6, using zero-based indices. It saves each key, checks preceding entries from right to left, and shifts only entries strictly greater than the key. It stops at the first entry no greater than the key or at the left edge.
Count rightward copies of existing entries as shifts; exclude writing the saved key. Count every evaluated comparison between an entry and the key, including a final false comparison when one occurs; exclude index checks.
Count writes across two ordered blocks
A data logger stores 100 distinct integer readings in this order: 61 through 100 in ascending order, followed by 1 through 60 in ascending order. It sorts them using the following insertion-sort implementation.
An array write is an execution of an assignment to an entry of a. Assignments to key, i, and j do not count. Count the final key assignment on every pass, even when it writes the existing value back into the same location.
Find the total number of array writes for this initial arrangement. Then find how many fewer array writes it needs than sorting the same readings initially arranged in descending order, from 100 down to 1. Give both answers as exact integer counts of array writes.