Beruflich Dokumente
Kultur Dokumente
(Searching Algorithms)
Common Problems - Reminder
There are some very common problems that we use
computers to solve:
Searching through a lot of records for a specific
record or set of records
Because list[1] 27, you compare 27 with the next element in the list
Suppose that the second element in the array list contains the
variable key, then we have performed two comparisons to find the
key.
Carry on the same analysis till the key is contained in the last element
of the array list. In this case, we have performed N comparisons (N is
the size of the array list) to find the key.
Finally if the key is NOT in the array list, then we would have
performed N comparisons and the key is NOT found and we would
return -1.
Performance Analysis - Linear Search
Therefore, the best case is: 1
And, the worst case is: N
The average case is:
Best case
Average Number of
1 + 2 + 3 + ..+ N + N
=
Comparisons
N+1
Worst case and key is NOT found!
Number of possible cases
Performance Analysis - Linear Search
list
3 19
4 use this as the middle of the array
25
5 Compare list[4] with 19
27
25 is bigger than 19 so use the bottom
half
Binary Search Pass 4
search key = 19
list
list
3 19
4 use this as the middle of the array
25
5 Compare list[4] with 18
27
25 is bigger than 18 so use the bottom
half
Binary Search Pass 4
search key = 18
list
if(key<list[mid])
return binarySearch(list, first, mid-1, key);
if(key>list[mid])
return binarySearch(list, mid+1, last, key);
}
Analysis using the Recurrence equation
public int binarySearch(int list[ ], int first, int, last, int key)
{
if(first > last) return FALSE; Cost = C1
T(n) = C1+C2+C3+T(n/2)
T(n) = C + T(n/2)
By Expansion
Using Iterative method
We reach T(1) when
Solution
Case 2 (k=0)