Академический Документы
Профессиональный Документы
Культура Документы
Márcio Ribeiro
marcio@ic.ufal.br 23 12 25 32 33 53 21 2 … 89
twitter.com/marciomribeiro 0 1 2 3 4 5 6 7 … 540
Systems need to search for customers, products, So, our systems should search for data!
23 12 25 32 33 53 21 2 … 89
0 1 2 3 4 5 6 7 … 540
OK! Thanks!
Sir, you’re at seat
number 6.
Linear search
Searching algorithms
23 12 25 32 33 53 21 2 … 89
0 1 2 3 4 5 6 7 … 540
Linear search
• Best case:
• When the element is at the first posiBon
• 1 comparison is needed
• Constant Bme (it does not depend on the array size!)
Using the Linear search… Now… instead of saying only “Yes” or “No”…
• … how many comparisons we should do to find 99? • Let’s imagine some hints like “LeX” and “Right”
How many )mes we asked for the element 99? Binary search
• We invesBgated two posiBons and we know that 99 can be • By choosing some posiBons, we narrow down the number
only at two posiBons: 3 or 4 of posiBons we need to take a look!
• That wasn’t true before when using the linear search! In • Quiz:
this case, we would sBll need to invesBgate 5 posiBons!!! • What is the best posiBon to take a look first? Why?
• What is the disadvantage of this algorithm?
No! No!
! " 0 1 2 3 4 5 6
0 1 2 3 4 5 6
int binary_search(int *v, int size, int element);
Recursive version… in Haskell!
int binary_search(int *v, int size, int element)
{ import Data.Array;
int begin = 0;
binarySearch array element begin end
int end = size – 1;
| begin > end = -1
int middle; | element > array!middle = binarySearch array element (middle + 1) end
| element < array!middle = binarySearch array element begin (end - 1)
while (begin <= end) { | otherwise = middle
middle = (begin + end) / 2; where
if (v[middle] < element) { middle = (begin + end) `div` 2
begin = middle + 1;
} else if (v[middle] > element) { binarySearch (array (0,5) [(0,12),(1,23),(2,45),(3,67),(4,99),(5,101)]) 12 0 5
end = middle - 1; 0
binarySearch (array (0,5) [(0,12),(1,23),(2,45),(3,67),(4,99),(5,101)]) 23 0 5
} else { 1
return middle; binarySearch (array (0,5) [(0,12),(1,23),(2,45),(3,67),(4,99),(5,101)]) 45 0 5
2
} binarySearch (array (0,5) [(0,12),(1,23),(2,45),(3,67),(4,99),(5,101)]) 67 0 5
} 3
binarySearch (array (0,5) [(0,12),(1,23),(2,45),(3,67),(4,99),(5,101)]) 99 0 5
return -1; 4
} binarySearch (array (0,5) [(0,12),(1,23),(2,45),(3,67),(4,99),(5,101)]) 101 0 5
5
binarySearch (array (0,5) [(0,12),(1,23),(2,45),(3,67),(4,99),(5,101)]) 102 0 5
-1
References
Chapter 10