- Sentinel Linear Search as the name suggests is a type of Linear Search
- where the number of comparisons are reduced as compared to a traditional linear search.
- When a linear search is performed:
34 56 21 09 76 1 98 50
Example: Array size= N,
In worst case, when we search 100 in array
(N + 1) comparisons are made for the index of the element to be comparedSo that the index is not out of bounds of the array which can be reduced in a Sentinel Linear Search.
The last element of the array is replaced with the element to be searched
Then the linear search is performed on the array without checking whether the current index is inside the index range of the array or not.
Because the element to be searched will definitely be found inside the array even if it was not present in the original array since the last element got replaced with it.
So, the index to be checked will never be out of bounds of the array.
The number of comparisons in the worst case here will be (N + 2).
34 56 21 09 76 1 98 50
The last element of the array is replaced with the element to be searched ( assume item=100)
34 56 21 09 76 1 98 100 // Values
0 1 2 3 4 5 6 7 //Index
int i = 0;
while(array[i]!=item)
{
i++;
}
// here i=7;
int last = array[N-1]; last=50
array[N-1] = item;
// Here item is the search element.
int i = 0;
No is found at ith location ie. i=n-1
array[N-1] = last; // We store original value here ie 50
if( (i < N-1) || (item == array[N-1]) ) // item=100 == 50
{
cout << " Item Found = "<<i;
}
else
{
cout << " Item Not Found";
}
L=[]
def get():
n=int(input("Enter class strength"))
for i in range(n):
roll=int(input("Enter roll no"))
L.append(roll)
def dis():
for i in L:
print(i,end=' ')
def sentinel():
item=int(input("Enter roll no you will search in list"))
last=L[-1]
L[-1]=item
i =0;
while(item!=L[i]):
i+=1
L[-1]=last
#i<n-1 ; i<len(l)-1
if(i<len(L)-1 or item==L[-1]):
print("Roll no is found at", i, "location")
else:
print("No is not found")
get()
dis()
sentinel()
0 Comments