Binary Search
Binary Search
Definition
The Binary Search algorithm is one of the most efficient search
algorithm which requires the list to be sorted in ascending
order. To search an element in the list the algorithm splits the
list into 2 and locates the middle element of the list. The middle
element is compared with the search element.
If the search element is less than the middle element the first
part of the list is searched. Else second part of the list is
searched.
This process is continued until the search element is equal to
the middle element of the list. This procedure is called Binary
Search.
Algorithm Binary Search(LB,UB,BEG,END,MID,DATA,LOC,ITEM)
LB – Lower bound value in the List
UB – Upper bound value in the List
BEG – Beginning of the list to find mid value
END – End of the list to find mid value
DATA – A linear array with N elements
ITEM – The information to be searched
LOC – Position of the item to be searched
DATA 11 22 30 33 40 44 55 60 66 77 80 88 99
1 2 3 4 5 6 7 8 9 10 11 12 13
ITEM = 40
Initially
I) BEG = 1 and END = 13 and MID = INT(1 +13)/2 = 7,
DATA[MID] = 55 Since 40<55 Step 1: Set BEG= LB, END = UB and MID =
INT((BEG+END))/2
Step 2: Repeat Step 3 and Step 4 while (BEG<= END)
2) BEG =1 , END = MID -1 = 7-1 = 6 and (DATA[MID]ITEM)
so new MID = INT(1+6)/2 = 3.5 = 3 Step 3: If (ITEM<DATA[MID]) then set END= MID-1
DATA[MID] = 30 Since 40>30 else set BEG = MID +1
Step 4: Set MID = INT(BEG+END)/2
Step 5: If DATA[MID]= ITEM the set LOC= MID
3)BEG = MID + 1=4 END = 6
else set LOC= NULL
so New MID = INT(4+6)/2 = 5, DATA[MID] = 40
ITEM = 85 1 2 3 4 5 6 7 8 9 10 11 12 13
Initially
I) BEG = 1 and END = 13 and MID = INT(1 +13)/2 = 7,
DATA[MID] = 55 85<55 F
Step 1: Set BEG= LB, END = UB and MID =
BEG = MID + 1 = 8 INT((BEG+END))/2
MID= INT(8+13)/2 = 10.5 = 10 Step 2: Repeat Step 3 and Step 4 while (BEG<= END)
DAT[MID] = 77 85<77 F and (DATA[MID]ITEM)
Step 3: If (ITEM<DATA[MID]) then set END= MID-1
BEG = MID +1 = 10+1 =11 else set BEG = MID +1
MID = INT(11+13)/2 = 24/2 =12 Step 4: Set MID = INT(BEG+END)/2
DATA[12] = 88 85<88 T Step 5: If DATA[MID]= ITEM the set LOC= MID
else set LOC= NULL
END = MID -1 = 12 -1 = 11
MID = INT(11+11) /2 =22/2 =11
DATA[11]=80 85<80 F