Name=
Usman Ahmad Siddiqui
Roll No. =
2018-ME-05
Submitted to=
Mr. Salman Ashar
Semester=
3rd
Session=
2018-2022
Topic=
Linear& Binary search, Sentinel value
Linear and binary search
Linear search
In computer science, a linear search or sequential search is a method for
finding an element within a list. It sequentially checks each element of the list until
a match is found or the whole list has been searched.
A simple approach is to do linear search, i.e.
Start from the leftmost element of arr[] and one by one compare x with each
element of arr[]
If x matches with an element, return the index.
If x doesn’t match with any of elements, return -1
Advantages
The advantages of linear search
is its simplicity:
conceptually
it's extraordinarily
easy to understand
implementation-wise
Disadvantages
The disadvantages of linear search
Very poor O (n) general efficiency (performance of the algorithm scales
linearly with the size of the input).
Linear search is considerably slower than many other search algorithms.
Binary search
In computer science, binary search, also known as half-interval search,
logarithmic search, or binary chop, is a search algorithm that finds the position of a
target value within a sorted array. Binary search compares the target value to the
middle element of the array.
A method to do binary search:
1. Compare x with the middle element.
2. If x matches with middle element, we return the mid index.
3. Else If x is greater than the mid element, then x can only lie in right half sub-
array after the mid element. So we recur for right half.
4. Else (x is smaller) recur for the left half
Advantages of binary search
A binary search is typically faster than a sequential search
Binary search has logarithmic time complexity
The advantage of a binary search over a linear search is astounding for large
numbers.
Disadvantages of binary search
Complexity
Algorithm requires the list to be sorted
Sentinel value
In computer programming, a sentinel value (also referred to as a flag value,
trip value, rogue value, signal value, or dummy data) is a special value in the
context of an algorithm which uses its presence as a condition of termination,
typically in a loop or recursive algorithm. For example, a loop may execute
while the value of a variable is not -1. Here -1 is the sentinel value.