U3 L1 Searching
U3 L1 Searching
searching
Searching means to find whether a particular value is present in an
array or not. If the value is present in the array, then searching is said
to be successful and the searching process gives the location of that
value in the array. However, if the value is not present in the array,
the searching process displays an appropriate message and in this
case searching is said to be unsuccessful.
There are two popular methods for searching the array elements:
1. linear search
2. binary search.
Linear search
Linear search, also called as sequential search, is a very simple
method used for searching an array for a particular value. It works by
comparing the value to be searched with every element of the array
one by one in a sequence until a match is found. Linear search is
mostly used to search an unordered list of elements (array in which
data elements are not sorted). For example, if an array A[] is declared
and initialized as,
int A[] = {10, 8, 2, 7, 3, 4, 9, 1, 6, 5};
Complexity of linear search
algorithm
Linear search executes in O(n) time where n is the number of
elements in the array. Obviously, the best case of linear search is
when VAL is equal to the first element of the array. In this case, only
one comparison will be made. Likewise, the worst case will happen
when either VAL is not present in the array or it is equal to the last
element of the array. In both the cases, n comparisons will have to be
made. However, the performance of the linear search algorithm can
be improved
by using a sorted array.
Binary Search
(a) If VAL < A[MID], then VAL will be present in the left segment of
the array. So, the value of END
will be changed as END = MID – 1.
(b) If VAL > A[MID], then VAL will be present in the right segment
of the array. So, the value of BEG will be changed as BEG =
MID + 1.
Complexity of binary search
algorithm
The complexity of the binary search algorithm can be expressed as
f(n), where n is the number of elements in the array. The complexity of
the algorithm is calculated depending on the number of comparisons
that are made. In the binary search algorithm, we see that with each
comparison, the size of the segment where search has to be made is
reduced to half. Thus, we can say that, in order to locate a particular
value in the array, the total number of comparisons that will be made
is given as
2f(n) > n or f(n) = log2n