CS FundamentalsVery hardProduct-company placement · Amazon-style

For the function below, what are its cyclomatic complexity and the number of times a[j] > a[j + 1] is evaluated for the input [2, 1, 3, 4, 5, 6]?

For the function below, what are its cyclomatic complexity and the number of times a[j] > a[j + 1] is evaluated for the input [2, 1, 3, 4, 5, 6]?
def bubble(a):
    n = len(a)
    for i in range(n - 1):
        swapped = False
        for j in range(n - 1 - i):
            if a[j] > a[j + 1]:
                a[j], a[j + 1] = a[j + 1], a[j]
                swapped = True
        if not swapped:
            break
    return a
  1. A. V(G) = 4, 15 comparisons
  2. B. V(G) = 5, 5 comparisons
  3. C. V(G) = 5, 9 comparisons
  4. D. V(G) = 4, 9 comparisons

Correct answer: C. V(G) = 5, 9 comparisons

Decisions: two for loops and two ifs, so V(G) = 5. Pass 1 makes 5 comparisons and one swap; pass 2 makes 4 comparisons with no swap and breaks, giving 9. 15 is the no-early-exit count; 5 assumes an already sorted list.

More Software Engineering, Git and Cloud Basics questions

Exams that ask this topic