Linear Search and Binary Search
Linear Search and Binary Search
Linear Search
Since the array elements are stored in linear order searching the
element in the linear order make it easy and efficient.
The search may be successful or unsuccessfully. That is, if the
required element is found them the search is successful other
wise it is unsuccessfully.
Advantages
element
element
element
element
element
element
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.
Binary Search Example
low high
middle
Searching for 18.
16
Binary Search Example
low high
middle
Searching for 18: found!
17
Time Complexity of Binary Search
19