Searching in Python


Searching

Searching is the process of finding a given value position in a list of values. It decides whether a search key is present in the data or not.

It is algorithmic process to finding a particular item in a collection of items.

To search an element in a given array, it can be done in two ways:

1. Simple Search 

2. Binary Search

Let us discuss one by one...

1. Simple Search

Simple search is also called Sequential search or Linear search. It is a basic and simple search algorithm.

Simple search starts at the beginning of the list and checks every element of the list. Simple search compares the element with all the other element given in the list. If the element is matched, it return the index value, else it returns -1 if the element is not found.

Example



The above figure shows how simple search works. It searches an element of value from an array till the desired element or value is not found.

If we search the element 25, it will go step by step in a sequence order. It searches in a sequence order.

Sequential search is applied on the sorted or unsorted list when there are fewer elements in a list.

 It will return 4 because the value 25 is on the 4th index position.

Algorithm for Linear search

Step 1 : Start from the leftmost element of given arr[] and one by one compare element x with each element of arr[].

Step 2 : If x matches with any of the element, return the index value.

Step 3 : If x does not match with any of elements in arr[], return -1 or element not found.

Implementation Program

def linearsearch(arr,x):

        for i in range(len(arr)):

                if (arr[i]==x):

                        return i

        return -1

arr=['p','y','t','h','o','n','c','l','a','s','s']

x='a'

print("element found at index"+str(linearsearch(arr,x)))

Output

element found at index 8























No comments:

Post a Comment