Unit 4 Cycle 2 Day 3: Off-by-One: Adjacent Comparison
Share
Off-by-One: Adjacent Comparison
Section 4.2 — Traversing Arrays
Key Concept
Adjacent element comparison algorithms compare arr[i] to arr[i + 1] and must stop at i < arr.length - 1 (not arr.length) to avoid an out-of-bounds exception. The AP exam deliberately tests this boundary: using i < arr.length crashes on the last iteration when arr[i + 1] accesses one past the end. Applications include finding consecutive duplicates, checking if an array is sorted, and computing differences between adjacent elements.
Consider the following method intended to check if an array is sorted ascending.
What is wrong with this method?
Answer: (A) The loop condition should be i < arr.length - 1.
Using i <= arr.length with arr[i+1] causes ArrayIndexOutOfBoundsException. The loop must stop at i < arr.length - 1 so arr[i+1] stays in bounds.
Why Not the Others?
(B) Using > is correct for ascending order.
(C) Returning true by default is correct: no unsorted pair found means sorted.
(D) The loop bound causes an out-of-bounds error.
Common Mistake
When comparing arr[i] with arr[i+1], loop to length - 1. This prevents arr[i+1] from exceeding the array bounds.
AP Exam Tip
Adjacent-pair loops: bound is length - 1. This off-by-one pattern is one of the most common AP exam traps.