0% found this document useful (0 votes)
29 views

A: La Lista Ordenada X: Lo Que Queremos Buscar """

This document contains Python code defining multiple functions for performing a binary search on a sorted list. The functions include binary_search, binary_search2, binary_search3, and binary_search_g. The binary_search function performs a basic iterative binary search, while binary_search2 and binary_search3 use slightly different approaches. binary_search_g allows specifying a custom comparison function.

Uploaded by

Pablo
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views

A: La Lista Ordenada X: Lo Que Queremos Buscar """

This document contains Python code defining multiple functions for performing a binary search on a sorted list. The functions include binary_search, binary_search2, binary_search3, and binary_search_g. The binary_search function performs a basic iterative binary search, while binary_search2 and binary_search3 use slightly different approaches. binary_search_g allows specifying a custom comparison function.

Uploaded by

Pablo
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

/home/pablo/Dropbox/02 - Docencia/Paradigmas de Programación/code/python/BS.

py

1 def binary_search(A,x):
2 """ busqueda en una lista ordenada
3 A: la lista ordenada
4 x: lo que queremos buscar
5 """
6 i = 0
7 j = len(A) - 1
8 while i <= j:
9 m = (i+j)/2
10 if x == A[m]:
11 return True
12 elif x < A[m]:
13 j = m - 1
14 else:
15 i = m + 1
16 return False
17
18 def binary_search2(A,x):
19 i = 0
20 j = len(A) - 1
21 while i < j:
22 m = (i+j)/2
23 if x > A[m]:
24 i = m + 1
25 else:
26 j = m
27 return x == A[i]
28
29 def binary_search3(A,x):
30 return bsearch(A, x, 0, len(A)-1)
31
32 def bsearch(A,x,i,j):
33 if i == j:
34 return x == A[i]
35 else:
36 m = (i+j)/2
37 if x > A[m]:
38 return bsearch(A, x, m+1, j)
39 else:
40 return bsearch(A, x, i, m)
41
42 def binary_search_g(A, x, comp = cmp):
43 i = 0
44 j = len(A) - 1
45 while i <= j:

1 of 2 02/21/2018 10:10 PM
/home/pablo/Dropbox/02 - Docencia/Paradigmas de Programación/code/python/BS.py

46 m = (i+j)/2
47 if comp(x, A[m]) == 0:
48 return True
49 elif comp(x, A[m]) < 0:
50 j = m - 1
51 else:
52 i = m + 1
53 return False
54

2 of 2 02/21/2018 10:10 PM

You might also like