Program to Search an Element in an Array

Write a program to search an element in an array. Given a sorted array, how do you search an element in an array. Think for a moment how do you solve this problem.

You can use multiple approaches to find the solution of this problem. But try to solve this problem in minimum time complexity.

First Approach : You can solve this problem in O(n) time using Linear Search.

Using Linear Search you can compare an element (value to searched for) with each element of an array . If the element is found then return the index/position of an element.

Search an Element in an Array using Linear Search

Linear search is a simple searching algorithm in which element (value to be searched) is compared with each element of an array. If the element is found then it’s index is returned. The time complexity of a Linear Search is O(n).

Find missing number in an array .

 

PHP Function to Implement Linear Search

 

Second Approach : You can solve this problem in O(logn) time using Binary Search.

Search an Element in an Array using Binary Search

We have seen the implementation of Linear search. Now we use Binary search algorithm which is more efficient than Linear Search. If you are not familiar with binary search, then check my previous posts the  link of which is given below.

If you are not familiar with a binary search, then check my previous posts the  link of which is given below.

Binary search algorithm & it’s time complexity

Implementation of Binary search using recursion .

Programming Questions.

Using array_search() to search an element in an array – PHP

array_search() function – It searches the array for a given value and returns the corresponding key if successful.

Tagged , , , , . Bookmark the permalink.

About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.