FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
algorithms/search/binary_search.py at master · amusi/algorithms · GitHub
amusi
algorithms
Repository navigation
Code
Pull requests
Actions
Projects
Wiki
Security and quality
Insights
Expand file tree
Breadcrumbs
algorithms
/
search
/
binary_search.py
Copy path
More file actions
More file actions
Latest commit
History
History
History
37 lines (32 loc) · 968 Bytes
Breadcrumbs
algorithms
/
search
/
binary_search.py
Copy path
File metadata and controls
37 lines (32 loc) · 968 Bytes
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#
# Binary search works for a sorted array.
# Note: The code logic is written for an array sorted in
# increasing order.
# T(n): O(log n)
#
def
binary_search
(
array
,
query
):
lo
,
hi
=
0
,
len
(
array
)
-
1
while
lo
<=
hi
:
mid
=
lo
+
(
hi
-
lo
)
//
2
val
=
array
[
mid
]
if
val
==
query
:
return
mid
elif
val
<
query
:
lo
=
mid
+
1
else
:
hi
=
mid
-
1
return
None
def
main
():
array
=
[
1
,
2
,
3
,
3
,
3
,
3
,
4
,
4
,
4
,
4
,
5
,
6
]
print
(
array
)
print
(
"-----SEARCH-----"
)
print
(
"found: "
,
5
,
" in index:"
,
binary_search
(
array
,
5
))
print
(
"-----SEARCH-----"
)
print
(
"found: "
,
6
,
" in index:"
,
binary_search
(
array
,
6
))
print
(
"-----SEARCH-----"
)
print
(
"found: "
,
7
,
" in index:"
,
binary_search
(
array
,
7
))
print
(
"-----SEARCH-----"
)
print
(
"found: "
,
-
1
,
" in index:"
,
binary_search
(
array
,
-
1
))
print
(
"-----SEARCH-----"
)
if
__name__
==
"__main__"
:
main
()
Back
|
FazBrowse Home
|
New Git URL