Average Case Analysis of Binary Search PDF
Average Case Analysis of Binary Search PDF
Average Case Analysis of Binary Search PDF
mid
low high
Iteration 1 0,7,14
Figure 2. A binary tree showing the number of iterations for each element in an array of 15
to be found via binary search
Table 1 summarizes the array elements and the respective number of iterations for them to be
found. The rightmost column shows the percentage of elements for each case. For instance,
about 50% (8 out of 15) of the nodes take 4 iterations in the binary search before being found.
Number of iterations Array elements Percentage of nodes
1 A[7] ~6.25%
2 A[3], A[11] ~12.5%
3 A[1], A[5], A[9], A[13] ~25%
4 A[0], A[2], A[4], A[6], A[8], A[10], A[12], ~ 50%
A[14]
Table 1. Array elements are divided into four cases, each with different number of
iterations.
∑𝑙𝑜𝑔𝑁
𝑖=1 (𝑛𝑢𝑚𝑏𝑒𝑟 𝑜𝑓 𝑖𝑡𝑒𝑟𝑎𝑡𝑖𝑜𝑛𝑠 𝑖𝑛 𝑐𝑎𝑠𝑒 𝑖) ∗ (𝑛𝑢𝑚𝑏𝑒𝑟 𝑜𝑓 𝑛𝑜𝑑𝑒𝑠 𝑖𝑛 𝑐𝑎𝑠𝑒 𝑖) / N
𝑙𝑜𝑔𝑁 𝑁
= ∑𝑖=1 𝑖 ∗ 2𝑖
/N
𝑁 𝑁 𝑁
= (1*2𝑙𝑜𝑔𝑁 + … + (logN-1)* 22 + logN* 2 ) / N <Sequence 1>
Take the array of 15 elements as an example, the average cost is shown below:
3. The conclusion
The average cost of a successful search is about the same as the worst case where an item is not
found in the array, both being roughly equal to logN.
So, the average and the worst case cost of binary search, in big-O notation, is O(logN).
Exercises:
1. Take an array of 31 elements. Generate a binary tree and a summary table similar to those
in Figure 2 and Table 1.
2. Calculate the average cost of successful binary search in a sorted array of 31 elements.
3. Given an array of N elements, prove that calculation of Sequence 1 shown above is
indeed O(logN).
Programming projects: