Grokking Algorithms



Yüklə 348,95 Kb.
Pdf görüntüsü
səhifə10/122
tarix05.12.2023
ölçüsü348,95 Kb.
#173611
1   ...   6   7   8   9   10   11   12   13   ...   122
grokking-algorithms-illustrated-programmers-curious

Chapter 1
 
 
I
 
 
Introduction to algorithms
8
Note
Binary search only works when your list is in sorted order. For example,
the names in a phone book are sorted in alphabetical order, so you can
use binary search to look for a name. What would happen if the names 
weren’t sorted?
Let’s see how to write binary search in Python. The code sample here 
uses arrays. If you don’t know how arrays work, don’t worry; they’re 
covered in the next chapter. You just need to know that you can store 
a sequence of elements in a row of consecutive buckets called an array. 
The buckets are numbered starting with 0: the first bucket is at position 
#0, the second is #1, the third is #2, and so on.
The 
binary_search
function takes a sorted array and an item. If the 
item is in the array, the function returns its position. You’ll keep track 
of what part of the array you have to search through. At the beginning
this is the entire array:
low = 0
high = len(list) - 1
Each time, you check the middle element:
mid = (low + high) / 2
guess = list[mid]
If the guess is too low, you update 
low
accordingly:
if guess < item:
low = mid + 1
mid is rounded down by Python 
automatically if (low + high) isn’t
an even number. 


9
And if the guess is too high, you update 
high
. Here’s the full code:
def binary_search(list, item):
low = 0
high = len(list)—1
while low <= high: 
mid = (low + high)
guess = list[mid]
if guess == item:
return mid
if guess > item:
high = mid - 1
else:
low = mid + 1

Yüklə 348,95 Kb.

Dostları ilə paylaş:
1   ...   6   7   8   9   10   11   12   13   ...   122




Verilənlər bazası müəlliflik hüququ ilə müdafiə olunur ©azkurs.org 2024
rəhbərliyinə müraciət

gir | qeydiyyatdan keç
    Ana səhifə


yükləyin