top of page

Search Operation


Searching is the process of finding the location of given element in the array.

The search is said to be successful if the given element is found i.e the element does exist in the array otherwise unsuccessful.


Linear search:

The way to search the given element item is to compare item with each element of a one by one is called linear serch.


#include<iostream>
using namespace std;

int linearSearch(int arr[],int item,int len)
{
    for(int i=0 ; i<len ;i++)
    {
        if(arr[i] == item)
        {
            return i;
        }
    }
    return -1;
}

int main()
{
    int arr[] = {2,5,8,9,2,6,7};
    int len = sizeof(arr)/sizeof(arr[0]);
    int pos = linearSearch(arr,9,len);
    if(pos != -1)
    {
        cout<<"Element found at pos:"<<pos<<endl;
    }
    else
    {
        cout<<"Element not found in array"<<endl;
    }
    return 0;
}

Binary Search:

Binary search is applicable for sorted array.


#include<iostream>
using namespace std;

int linearSearch(int arr[],int item,int len)
{
    int begin = 0;
    int end = len-1;
    
    int mid = (begin+end)/2;
    
    while(arr[mid] != item && (begin <= end))
    {
        if(item < arr[mid])
            end = mid - 1;
        else
            begin = mid + 1;
        mid = (begin+end)/2;
    }
    if(begin > end)
    {
        return -1;
    }
    else
        return mid;
}

int main()
{
    int arr[] = {2,3,5,6,8,9,12};
    int len = sizeof(arr)/sizeof(arr[0]);
    int pos = linearSearch(arr,3,len);
    if(pos != -1)
    {
        cout<<"Element found at pos:"<<pos<<endl;
    }
    else
    {
        cout<<"Element not found in array"<<endl;
    }
    return 0;
}

Comentarios


bottom of page