Home » Data Structure & Algorithms » Searching Algorithms

Searching Algorithms

 

In this chapter we are going to see the linear search and binary search algorithms.
1 : Linear Search
2 : Binary Search

Linear Search :

Question :
There is an array of integers.You are given an element.Search the element in the array in 0(n) complexity and return its index.

Algorithm :
Step 1 : Traverse the array one by one element and compare each element of the array  with the number to be searched.
Step 2 : Once we get equality ,we are printing the element and its position in the array.

The method linearSearchFirst() is accepting two arguments .First argument is the array and second argument is the element to be searched.The element to be searched is compared with each element in the array and once we find the match, we are exiting from the for loop.

The method linearSearchAll() is accepting two arguments .First argument is the array and second argument is the element to be searched..The element to be searched is compared with each element in the array and whenever we get equalities, we are printing its occurrence.If the element is not present in the array ,we are printing the negative message.

Program :

OutPut:

 
 


1 Comment

Leave a comment

Your email address will not be published. Required fields are marked *

eleven − four =