Sequential Search or linear search program in python - python coding

Sequential Search or linear search program in python - python coding


Published at - Sep 07, 2021

In this lesson on python coding, we will talk about one of the fundamental algorithms in computer science linear search or sequential search with algorithm. Linear Search search algorithm is a very common question for python coding interviews. This article will help if you are preparing for a python coding interview, so let's try to write a simple python program to implement the linear search tree in python.
 
These are some highlighted points about linear search algorithm
  • Search items in sequence.
  • Complexity of the sequential search, is O(n).
  • Sequential search can be improved by ordering the list in the case when the searched item is absent.

Algorithm

Linear Search ( Array A, Value x)

Step 1: Set i to 1
Step 2: if i > n then go to step 7
Step 3: if A[i] = x then go to step 6
Step 4: Set i to i + 1
Step 5: Go to Step 2
Step 6: Print Element x Found at index i and go to step 8
Step 7: Print element not found
Step 8: Exit

Method 1 - Linear Serach

def lin_search(search_list,item):
	pos = 0
	found = False
	
	while(pos<len(search_list) and not found):
		if search_list[pos] == item:
			found = True
		pos = pos +1
	
	return found

print lin_search([1,2,3,5,8],6)
print lin_search([1,2,3,5,8],5)

Method 2 - Linear Search

def lin_search(target, array)
  counter = 0
  results = []

  while counter < array.length
    if array[counter] == target
      results << counter
      counter += 1
    else
      counter += 1
    end
  end

  if results.empty?
    return False
  else
    return True
  end
end

print lin_search([1,2,3,5,8],6)
print lin_search([1,2,3,5,8],5)

 The above python program will search for your given input in the array and provides the boolean value if the given input is found in the given list or not.

Thank you for reading.



About author

Harendra
Harendra Kanojiya

Hi I'm Harendra Kumar Kanojiya. Currently I am FSD (Full-stack developer) and I have expertise with Angular ,PHP, Node JS, Laravel, Codeigniter and front end. Done few live projects and portfolio work in above.



Related Posts -

Follow Us

Follow us on facebook Click Here

Facebook QR
Scan from mobile
Join our telegram channel Click Here
Telegram QR
Scan from mobile