2 Wk10 Binary - Search - Lecture
2 Wk10 Binary - Search - Lecture
Dr Rob Blair
r.blair@uea.ac.uk SCI 2.19
1
Objectives
introduce a divide and conquer technique
2
Binary Search Specification
3
Binary Search Inputs
element key
4
Binary Search Outputs
5
Binary Search Description
6
4 9 9 10 12 15 22 23 24 27
7
10
4 9 9 10 12 15 22 23 24 27
8
10
4 9 9 10 12 15 22 23 24 27
9
10
4 9 9 10 12 15 22 23 24 27
10
10
4 9 9 10 12
11
10
4 9 9 10 12
12
10
4 9 9 10 12
13
10
10 12
14
10
10 12
15
10
16
Pseudo Code
17
binary_search(key, values):
start, end := 0, n
while start <= end:
mid := (start + end) / 2
if key == values[mid]:
return true
else if key < values[mid]:
end = mid - 1
else:
start = mid + 1
return false
18
binary_search(key, values):
start, end := 0, n
while start <= end:
mid := (start + end) / 2
if key == values[mid]:
return true
else if key < values[mid]:
end = mid - 1
else:
start = mid + 1
return false
19
binary_search(key, values):
start, end := 0, n
while start <= end:
mid := (start + end) / 2
if key == values[mid]:
return true
else if key < values[mid]:
end = mid - 1
else:
start = mid + 1
return false
20
binary_search(key, values):
start, end := 0, n
while start <= end:
mid := (start + end) / 2
if key == values[mid]:
return true
else if key < values[mid]:
end = mid - 1
else:
start = mid + 1
return false
21
binary_search(key, values):
start, end := 0, n
while start <= end:
mid := (start + end) / 2
if key == values[mid]:
return true
else if key < values[mid]:
end = mid - 1
else:
start = mid + 1
return false
22
binary_search(key, values):
start, end := 0, n
while start <= end:
mid := (start + end) / 2
if key == values[mid]:
return true
else if key < values[mid]:
end = mid - 1
else:
start = mid + 1
return false
23
binary_search(key, values):
start, end := 0, n
while start <= end:
mid := (start + end) / 2
if key == values[mid]:
return true
else if key < values[mid]:
end = mid - 1
else:
start = mid + 1
return false
24
Binary Search Recursive
25
bin_search(key, values, start, end):
31
Time Complexity
n
1= x
2
32
Time Complexity
x
2 =n
33
Time Complexity
x
log2(2 ) = log2(n)
34
Time Complexity
x
log2(2 ) = log2(n)
x × log2(2) = log2(n)
35
Time Complexity
x
log2(2 ) = log2(n)
x × log2(2) = log2(n)
x = log2(n)
36
Time Complexity
(log2(n))
𝒪
37
Time Complexity
38