UNIT 3 Linear-Search-And-Binary-Search
UNIT 3 Linear-Search-And-Binary-Search
Sorting
Linear Search
• Consider-
• There is a linear array ‘a’ of size ‘n’.
• Linear search algorithm is being used to search an element ‘item’
in this linear array.
• If search ends in success, it sets loc to the index of the element
otherwise it sets loc to -1.
• Then, Linear Search Algorithm is as follows-
Begin
for i = 0 to (n - 1) by 1 do
if (a[i] = item) then
set loc = i
Exit
endif
endfor
set loc = -1
End
Advantages
elemen
t
element
elemen
t
elemen
t
elemen
t
elemen
t
In the best case, the target value is in the first element of the array.
So the search takes some tiny, and constant, amount of time.
In the worst case, the target value is in the last element of the array.
So the search takes an amount of time proportional to the length of the
array.
Analysis of Linear
Search
The general term for a smart search through sorted data is a binary search.
1. The initial search region is the whole array.
2. Look at the data value in the middle of the search region.
3. If you’ve found your target, stop.
4. If your target is less than the middle data value, the new search region is
the lower half of the data.
5. If your target is greater than the middle data value, the new
search region is the higher half of the data.
6. Continue from Step 2.
Algorithm
Begin
Set beg = 0
Set end = n-1
Set mid = (beg + end) / 2
while ( (beg <= end) and (a[mid] ≠ item) ) do
if (item < a[mid]) then
Set end = mid - 1
else
Set beg = mid + 1
endif
Set mid = (beg + end) / 2
endwhile
if (beg > end) then
Set loc = -1
Binary Search
Example
lo middl hig
w e h
Searching for
21
18.
Binary Search
Example
lo hig
w h
middl
e
Searching for
22 18.
Binary Search
Example
lo hig
wmiddleh