Unit 3 Searching
Unit 3 Searching
Unit 3 Searching
o Linear Search
o Binary Search
Both techniques are widely used to search an element in the given list.
What is a Linear Search?
Linear search is a method of finding elements within a list. It is also called a sequential
search. It is the simplest searching algorithm because it searches the desired element in a
sequential manner.
It compares each and every element with the value that we are searching for. If both are
matched, the element is found, and the algorithm returns the key's index position.
Concept of Linear Search
Let's understand the following steps to find the element key = 7 in the given list.
Step - 1: Start the search from the first element and Check key = 7 with each element of list
x.
o Recursive Method
o Iterative Method
The divide and conquer approach technique is followed by the recursive method. In
this method, a function is called itself again and again until it found an element in
the list.
Binary search is more effective than the linear search because we don't need to
search each list index. The list must be sorted to achieve the binary search algorithm.
We have a sorted list of elements, and we are looking for the index position of 45.
So, we are setting two pointers in our list. One pointer is used to denote the smaller
value called low and the second pointer is used to denote the highest value
called high.
Now, we will compare the searched element to the mid index value. In this case, 32 is
not equal to 45. So we need to do further comparison to find the element.
If the number we are searching equal to the mid. Then return mid otherwise move to
the further comparison.
The number to be search is greater than the middle number, we compare the n with
the middle element of the elements on the right side of mid and set low to low =
mid + 1.
Otherwise, compare the n with the middle element of the elements on the left side
of mid and set high to high = mid - 1.