(20 points) Calculate the exact average-case time complexity of the binary search algorithm shown in Weiss, Figure 5.11. Only consider successful searches (where the item we are looking for is actually in the array) and assume all elements are equally likely to be the one we are searching for.
Hint: For each i, count how
many of the array elements will be found after binary search examines
exactly i array elements. (For example, the middle element is the only
one to be found after examining one array element, and there are two
elements that can be found afterexaming two array elements.) Then sum
over all and divide to find the average. For the generalization, you'll
use a
summation.
Potentially
useful fact: Depending on how you work this problem, you
may find the following useful:
Of course, you must explain how the formula is useful.
(Hint: Weiss 5.6.2 about binary search gives the big-oh answer for this
problem, so you can use that as a sanity check.)
These problems are for you to think about and convince yourself that you could do them. It would be good practice to actually do them, but you are not required to turn them in.
java.util.Map
to complete
this problem. Weiss exercise 6.2 [6.2]. You can just write the code for part (a) out by hand if you wish, but I recommend getting it working in Eclipse and printing out your code. Here is some code that you can use to test your method if you wish:
public static void main(String[] args) {
Collection<Collection<String>> a = new ArrayList<Collection<String>>();
String[][] arrays = {{"abc", "def", "ghi"},
{"xyz", "uvw", "abc", "abc"},
{"a", "ab", "abc", "xyz", "abc"}};
for (String[] sArray : arrays){
Collection<String> a1 = new ArrayList<String>();
for (String s: sArray)
a1.add(s);
a.add(a1);
}
System.out.println(count(a, "abc"));
}