Comparisons include unsuccessful tests

A program sorts response times [2, 4, 6, 8, 10, 1], measured in milliseconds, using this insertion-sort code:


Python
for i in range(1, len(a)):
    key = a[i]
    j = i - 1
    while j >= 0 and a[j] > key:
        a[j + 1] = a[j]
        j -= 1
    a[j + 1] = key


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.

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: