SEARCHING TECHNIQUES
LINEAR SEARCH
The simplest search problem is the sequential or linear search algorithm.
When the sequence is unsorted the standard approach for searching a target value is
sequential search.
This technique iterates over the sequence, one item at a time, until the specific item is
found or all items have been examined.
In Python, a target item can be found in a sequence using the in operator
if key in A :
print( "The key is in the array." )
else :
print( "The key is not in the array." )
The use of the in operator is, it makes the code simple and easy to read but it hides
the inner workings.
Example
To search element 31 in the array, the search begins with the value in the first
position. Since the first element does not contain the target value, the next element in
sequential order is compared to value 31. This process is repeated until the item is
found in the sixth position.
Similarly, to search element 8 in the same array, then the search begins in the same
manner, starting with the first element until the desired element is found or end of the
sequence. Here it is an unsuccessful search.
Implementation
def linearsearch(A,key):
1
found=0
for i in range(len(A)):
if A[i] == key:
found+=1
else:
continue
if found==0:
print("Key not found")
else:
print("Key found")
num=[10,51,2,18,4,31,13,5,23,64,29]
linearsearch(num,31)
BINARY SEARCH
• The binary search is used to efficiently locate a target value within a sorted sequence
of n elements. Here the sequence is sorted and indexible.
• For any index j, all the values stored at indices 0 to j-1 are less than or equal to the
value at index j, and all the values stored at indices j+1 to n-1 are greater than equal to
that at index j. This allows to quickly search target value.
• The algorithm maintains two parameters, low and high, such that all the candidate
entries have index at least low and at most high. Initially, low = 0 and high = n−1.
Then compare the target value to the median candidate, that is, the item data[mid]
with index
mid = (low+high)/2.
Example
• To search 10 in a sorted list of elements, first determine the middle element of the
list. As the middle item contains 18, which is greater than the target value 10, so
discard the second half of the list and repeat the process to first half of the list. This
2
process is repeated until the desired target item is located in the list. If the item is
found then it returns True, otherwise it returns False.
Searching for 10 in a sorted array using the binary search
Implementation
def binarysearch(data, target, low, high):
if low > high:
return False
else:
mid = (low + high) // 2
if target == data[mid]:
return True
elif target < data[mid]:
return binarysearch(data, target, low, mid − 1)
else:
return binarysearch(data, target, mid + 1, high)
This binary search algorithm requires O(log n) time. Whereas the sequential search
algorithm uses O(n) time.