CS FundamentalsVery hardProduct-company placement · GATE CS
Which loop invariant lets you prove this binary search correct for a sorted list a?
Which loop invariant lets you prove this binary search correct for a sorted list a?
lo, hi = 0, len(a) - 1
while lo <= hi:
mid = (lo + hi) // 2
if a[mid] < t: lo = mid + 1
elif a[mid] > t: hi = mid - 1
else: return mid
return -1- A. lo < hi throughout the loop
- B. a[lo] ≤ t ≤ a[hi] throughout the loop
- C. If t occurs in a, it occurs in a[lo..hi]
- D. mid always points to t's position
Correct answer: C. If t occurs in a, it occurs in a[lo..hi]
Each update discards only positions that cannot hold t because the list is sorted, so 'if t is in a, it is in a[lo..hi]' is preserved. When lo > hi the range is empty, proving -1 is correct. a[lo] ≤ t ≤ a[hi] fails when t is absent.
Practise more Software Engineering, Git and Cloud Basics questionsSoftware Engineering, Git and Cloud Basics: notes and key points
More Software Engineering, Git and Cloud Basics questions
- A team has 40 open defects; 15 new ones arrive and 25 are fixed each week. If these rates hold, how long until the backlog is cleared?
- Which statement correctly contrasts a centralised VCS such as Subversion with Git?
- Two artists keep overwriting each other's edits to the same layered .psd file in Git. Why does the usual merge workflow fail, and what…
- Priya rebases Rahul's three commits onto the latest main. What happens to the author and committer fields of the rewritten commits?
- Business rules like 'premium customer AND (order > ₹10,000 OR festive season)' are built as small objects with isSatisfiedBy(candidate)…
- A service reuses expensive database connections from a pool instead of opening one per request. One request leaves a connection inside an…