
8.6 Searching and Sorting Arrays 527
return i;
}
return -1; // end of array reached without finding key
// or an element larger than the key was found
}
In fact, if the array is sorted, it can be searched even more efficiently using
an algorithm called Binary Search, which we explain in the next section.
8.6.6 Binary Search of a Sorted Array
If you’ve played the “Guess a Number” game, you probably have used the
concept of a Binary Search. In this game, someone asks you to guess a
secret number between 1 and 100. For each number you guess, they tell
you whether the secret number is larger or smaller than your guess. A
good strategy is to guess the number ...