05 Linear & Binary Search
05 Linear & Binary Search
FACULTY OF S CIENCE ,
S HARQ I NSTITUTE OF H IGHER E DUCATION
Search Algorithms
Searching are designed to check for an element or retrieve an element from any
data structure where it is stored.
If the element is found in the list, it means searching was successful, otherwise
unsuccessful
There are two methods for searching:
1. Linear Search
2. Binary Search
In this type of search, a sequential search is made over all item one by one.
Every item is checked and if a match is found then that particular item is
returned, otherwise the search continuous till the end of the data collection.
SEQSEARCH(A[] , N , ITEM )
SET FLAG = 1
REPEAT FOR K = 0,1,2,3 ….. N-1
{
IF A[K] == ITEM THEN
SET FLAG = 0
WRITE “ SEARCH SUCCESSFUL, A[K] ”
}
IF FLAG == 1 THEN
WRITE “ SEARCH UNSUCCESSFUL ”
EXIT 12/10/2018 5
BY: SAMADI
A NALYSIS OF L INEAR S EARCH A LGORITHM
Best Case:
Suppose c1 is the required time for Step1, c2 for Step2, c3 for Step3, c4 for
Step4
So T(1) = c1 + c2 + c3 + c4
The best case happens when we found the ITEM in position K[1], and hence it
takes O(1) running time
Worst Case:
The worst case happens when we find ITEM in the last position of the array
A[1:N]
Since N comparisons were required, so the time required for the Steps will be:
For Step1 the time is c1, because this step is executed only once
For Step2 the time is c2n, because it will take amount of time proportional to n
Worst Case:
For Step3 the time is c3(n-1), because it is executed one less than Step2
For Step4 the time is c4(n-1), because it is executed one less than Step2
For Step5 the time is c5
c1, c2, c3, c4, and c5 are the constant times
The variables BEG and END denote the beginning and end locations of the
segment under search
The algorithm compares ITEM with the middle element DATA[mid] of the
segment
The MID position can be obtained as:
MID = INTEGER ( (beg + end) / 2)
If DATA[mid] = ITEM, then the search is successful and LOC is set to MID,
otherwise a new segment of DATA is obtained as follows:
If ITEM<DATA[mid], then ITEM may be present only in the left half of the
segment
BY: SAMADI 12/10/2018 13
B INARY S EARCH
And the END is set to MID – 1 and the searching is started again
If ITEM>DATA[mid], then ITEM may be present only in the right half of the
segment
DATA[mid+1], DATA[mid+2], .….., DATA[end]
And the BEG is set to MID + 1 and the searching is started again
Step-2: Since 40<55, now END has changed its value by END = MID – 1 = 7 – 1 =
6
hence MID = INTEGER ( (1 + 6) / 2) = 3
MID = 3 and so DATA[MID] = 30
Step-3: Since 40>30, now BEG will change its value by BEG = MID + 1 = 3 + 1 =
4
hence MID = INTEGER ( (4 + 6) /2) = 5
MID = 5 and so DATA[MID] = 40
The ITEM has been found in the DATA array, so LOC is set to MID and we get
LOC = 5
BY: SAMADI 12/10/2018 16
T HE E ND