|
| 1 | +# Copyright 2013, Michael H. Goldwasser |
| 2 | +# |
| 3 | +# Developed for use with the book: |
| 4 | +# |
| 5 | +# Data Structures and Algorithms in Python |
| 6 | +# Michael T. Goodrich, Roberto Tamassia, and Michael H. Goldwasser |
| 7 | +# John Wiley & Sons, 2013 |
| 8 | +# |
| 9 | +# This program is free software: you can redistribute it and/or modify |
| 10 | +# it under the terms of the GNU General Public License as published by |
| 11 | +# the Free Software Foundation, either version 3 of the License, or |
| 12 | +# (at your option) any later version. |
| 13 | +# |
| 14 | +# This program is distributed in the hope that it will be useful, |
| 15 | +# but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 16 | +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 17 | +# GNU General Public License for more details. |
| 18 | +# |
| 19 | +# You should have received a copy of the GNU General Public License |
| 20 | +# along with this program. If not, see <http://www.gnu.org/licenses/>. |
| 21 | + |
| 22 | +def binary_search(data, target, low, high): |
| 23 | + """Return True if target is found in indicated portion of a Python list. |
| 24 | +
|
| 25 | + The search only considers the portion from data[low] to data[high] inclusive. |
| 26 | + """ |
| 27 | + if low > high: |
| 28 | + return False # interval is empty; no match |
| 29 | + else: |
| 30 | + mid = (low + high) // 2 |
| 31 | + if target == data[mid]: # found a match |
| 32 | + return True |
| 33 | + elif target < data[mid]: |
| 34 | + # recur on the portion left of the middle |
| 35 | + return binary_search(data, target, low, mid - 1) |
| 36 | + else: |
| 37 | + # recur on the portion right of the middle |
| 38 | + return binary_search(data, target, mid + 1, high) |
0 commit comments