Sentinel Linear Search In C Program

Sentinel Linear Search is part of Linear Search, it reduces the old comparison process of Linear Search. In this post, we are going to write a c program to implement linear search with sentinels.

What is sentinel search in C?

Like Linear Search, Sentinel search is also a sequential search algorithm. It compares each element one after another. Our workload is reduced since we have fewer comparisons to make. This specialty makes this search algorithm better and faster than linear search.

//function to sentinel search x in the given array

void sentinel(int arr[], int n, int key)
{
  //last element of the array
  int last = arr[n - 1], i = 0;

  //element to be searched is placed at the last index
  arr[n - 1] = key;
  while (arr[i] != key)
    i++;

  //put the last element back
  arr[n - 1] = last;
  if ((i < n - 1) || (arr[n - 1] == key))
    printf ("%d is present at %d index", key, i);
  else
    printf ("element is not found!!!");
}

void main()
{
  int arr[] = { 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 };
  int n = 10;
  int key = 20;
  sentinel(arr, n, key);
  getch ();
}

C

Output

20 is present at 1 index

In the above program, we have taken two variables ‘n’ and ‘key’ these two variables are used to pass the array.

last=a[n-1], here we use the last element of the array in the variable name last. Then we replace a[n-1] with the new variable ‘Key’.

Other steps are quite easy to understand.

This is all about Sentinel Linear Search, if you find this post helpful then let me know in the comment section. And if you have any issues regarding this topic let me know in the comment section.

Leave a Comment