Searching is a very important problem in field of computer science.
Searching can be divided into three main categories :
1) Linear search
2) Binary search
This post will explain Linear search.
Linear search is simply iterating through all the elements of array , till you find the item in question.
Worst case complexity of this algorithm is O(N) while best case is O(1).
For example : Given a List of N elements find element x. If present, return its position.
Lets write a simple method to implement Linear search. See following method LinearSearch() this method takes two parameters, first is an array of integers and second is the element to search in that array.
int LinearSearch(int a, int k)
// Travel the array from start to end
// For every element of array check if current element of array is equal to k or not
if(a[i] == k)
// Element Found.
So above method returns -1 if element is not present in the array or returns its position in array, if present. Linear search is very simple to understand and implement.