MITx 6.00.1x Python Notes: Determining a Character in a String

Problem:
Using the idea of bisection search to determine if a character is in a string, so long as the string is sorted in alphabetical order.

Solution:First, test the middle character of a string against the character we are looking for (the "test character"). If they are the same, we are done - we've found the character we're looking for!
If they're not the same, check if the test character is "smaller" than the middle character. If so, we need only consider the lower half of the string; otherwise, we only consider the upper half of the string.

Python code



没有评论:

发表评论