Linear Binary
Linear Binary
1
© 2006 Pearson Addison-Wesley. All rights reserved
Linear Search
• The algorithm translates to the following Java method:
public static int linearSearch(Object[] array,
Object key)
{
for(int k = 0; k < array.length; k++)
if(array[k].equals(key))
return k;
return -1;
}
2
© 2006 Pearson Addison-Wesley. All rights reserved
• Best Case: In the best case, the key might be present at
the first index. So the best case complexity is O(1)
• Worst Case: In the worst case, the key might be present
at the last index i.e., opposite to the end from which the
search has started in the list. So the worst-case
complexity is O(N) where N is the size of the list.
3
© 2006 Pearson Addison-Wesley. All rights reserved
Binary Search
4
© 2006 Pearson Addison-Wesley. All rights reserved
Binary Search
5
© 2006 Pearson Addison-Wesley. All rights reserved
Binary Search
6
© 2006 Pearson Addison-Wesley. All rights reserved
Pseudocode for Binary Search
7
© 2006 Pearson Addison-Wesley. All rights reserved
Recursive Method for Binary Search
8
© 2006 Pearson Addison-Wesley. All rights reserved
Execution of the Method search
(Part 1 of 2)
9
© 2006 Pearson Addison-Wesley. All rights reserved
Execution of the Method search
(Part 1 of 2)
10
© 2006 Pearson Addison-Wesley. All rights reserved
Checking the search Method
11
© 2006 Pearson Addison-Wesley. All rights reserved
Checking the search Method
12
© 2006 Pearson Addison-Wesley. All rights reserved
Checking the search Method
13
© 2006 Pearson Addison-Wesley. All rights reserved
Checking the search Method
14
© 2006 Pearson Addison-Wesley. All rights reserved
Efficiency of Binary Search
15
© 2006 Pearson Addison-Wesley. All rights reserved
Efficiency of Binary Search
16
© 2006 Pearson Addison-Wesley. All rights reserved
Iterative Version of Binary Search
17
© 2006 Pearson Addison-Wesley. All rights reserved