~/ learn/ comp-372/ cards/ Insertion sort & the loop-invariant method
1 of 6

Type the inner shift-and-insert core of INSERTION-SORT

Type the inner shift-and-insert core of INSERTION-SORT

Answer

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

The guard `j >= 0` is tested first (short-circuit), so the loop never reads out of bounds; `a[j] > key` stops the scan at the insertion point. Dropping either guard breaks the algorithm: lose `j >= 0` and you index past the front; lose `a[j] > key` and you shift everything, destroying the order.

space flip · ← → navigate · esc to exit
NORMAL ~/memra/library/6d5f35e3-d1af-4fe7-892b-7485e9db3edc/flashcard utf-8 LF