Linear Search
• The sequential search (also called the linear search) is the
simplest search algorithm when we have no knowledge about
the array that whether it is sorted or not.
• It is also the least efficient.
• It simply examines each element sequentially, starting with the
first element, until it finds the key element or it reaches the end
of the array.
Example: If you were looking for someone on a moving
passenger train, you would use a sequential search.
Algorithm
A linear array DATA with N elements and a specific
ITEM of information are given. This algorithm finds the
location LOC of ITEM in the array DATA or sets LOC = 0.
Disadvantage
1. Keeping data in sorted array is very expensive when there are many
insertions and deletions.
Algorithm
(Binary search) BINARY(DATA, LB, UB, ITEM, LOC)
Here DATA is a sorted array with lower bound LB and upper bound UB, and ITEM is
a given item of information. The variables BEG, END and MID denote, resp., the
beginning, end, and middle locations of a segment of elements of DATA. The algo
finds the location LOC of ITEM in DATA or sets LOC = NULL.
• Final Result
• definition of logarithm, says that:
“A quantity representing the power to
which a fixed number (the base) must
be raised to produce a given number.”
• Which makes our equation into
logarithmic form.
• Average Case: Here, again the number
of comparisons is O(log n), because it
halves it halves the array until it is able
to get the element in the array.
Comparison between Binary and
Linear search
Binary search operates on sorted lists. Linear search can operate on unsorted
lists as well.
Binary search is complex as compared to Linear search is simple and
linear search. straightforward to implement than the
binary search.
Binary search is considered to be a more But, linear search is too slow to be used
efficient method that could be used with with large lists due to its O(n) average
large lists. case performance.
Number of comparisons are less. More number of comparisons are
required if the items are present in the
later part of the array or its elements are
more.
Works well with arrays and not on linked Works with arrays and linked lists.
lists.