Sunday, 8 December 2019

Sentinel search | Sentinel Linear search explained with Program


Sentinel search or Sentinel Linear search is modified version of Linear search.Here the idea is to reduce the total number of comparison required to find element. This algorithm replace the last element of the array with the search element itself and run loop without checking index range of array because the element to be searched will definitely found at last position of array if search element is found then loop is terminated.

Program:
   while loop is used because sentinel search does not require to check index range of array.


#include

using namespace std;

int main()
{
    int arr[10],n,key,last;
    int no,i,j=0;
    cout<<"enter number of elements"<
    cin>>n;
    cout<<"enter the elements of array"<
    for(i=0;i
    {
        cin>>arr[i];
    }
    cout<<"enter number to be searched:";
    cin>>key;
    last=arr[n-1];
    arr[n-1]=key;
    while(arr[j]!=key)
    {
        j++;
    }
     arr[n-1]=last;
    if( (j
    {
        cout<
    }
    else
    {
        cout<<"number not found"<
    }
    
    return 0;

}

Output:



No comments:

Post a Comment