This document discusses and compares linear search and binary search algorithms. Linear search sequentially compares an element to all elements in a data set to find a match, with average complexity of O(N/2). Binary search works on a sorted data set, comparing the target element to the middle element first and then either the left or right subset, with average complexity of O(logN). Binary search is faster but requires pre-sorting while linear search can work on unsorted data. Examples and pseudocode are provided for both algorithms.
2. WHAT IS “SEARCHING” IN DATA
STRUCTURES?
It is a process of finding/ efficient retrieval of a specific
data item from a set of data (Ordered / Un-Ordered)
E.g. – Finding a specific record from database.
4. LINEAR SEARCH
Simplest Algorithm.
Search item is compared with each item in data set
sequentially till match is found.
5. ALGORITHM FOR LINEAR SEARCH
for (each item in list)
{
compare search term to current item
if match,
save index of matching item
break
}
return index of matching item, or -1 if item not found
6. PERFORMANCE ANALYSIS OF LINEAR SEARCH
Best case: Occurs when the search term is in the first
slot in the array.
(Number of comparisons: 1)
Worst case: Occurs when the search term is in the last
slot in the array, or is not in the array.
(Number of comparisons: N)
Average case: Occurs when the search term will be
somewhere in the middle of the array.
(Number of comparisons: Approximately N/2)
7. BINARY SEARCH
Finds position of target data within a sorted list of data.
It compares search item with mid item in data set, if it is
small then it looks in left subset otherwise in right
subset. It is repeated until subset reduces to 0.
8. ALGORITHM FOR BINARY SEARCH
set first = 1, last = N, mid = N/2
while (item not found and first < last)
{
compare search term to item at mid
if match
save index
break
else if search term is less than item at mid,
set last = mid-1
else
set first = mid+1
set mid = (first+last)/2
}
return index of matching item, or -1 if not found
9. PERFORMANCE ANALYSIS OF BINARY SEARCH
Best case: Occurs when the search term is in the middle
slot in the array.
(Number of comparisons: 1)
Worst case: Occurs when the search term is in the
first/last slot in the array, or away from middle slot or is
not in the array.
(Number of comparisons: Log N)
Average case: Occurs when the search term will be
anywhere in the array.
(Number of comparisons: Almost same as Worst case i.e. Log
N)
12. Conclusion
• Binary Search requires input data to be sorted,
Linear Search doesn’t.
• Binary Search has complexity O(Log N); Linear
Search has complexity O(N).
• Binary Search Requires Random access of
data; Linear Search requires Sequential access
of data.
13. References
•Searching and Sorting Algorithms
(By Amy Csizmar Dalal)
•Searching Techniques: Binary Search
(By Nor Bahiah Hj Ahmad & Dayang Norhayati A. Jawawi)