Unit2 Linear Search
Unit2 Linear Search
• start from the first element and compare K with each element of the array.
• The value of K, i.e., 41, is not matched with the first element of the array. So,
move to the next element. And follow the same process until the respective
element is found.
• Now, the element to be searched is found.
• So algorithm will return the index of the element matched
Time Complexity
• Best Case Complexity –
• In Linear search, best case occurs when the element we are finding is
at the first position of the array.
• The best-case time complexity of linear search is O(1).
• Worst Case Complexity - In Linear search, the worst case occurs when
the element we are looking is present at the end of the array.
• The worst-case in linear search could be when the target element is
not present in the given array, and we have to traverse the entire
array.
• The worst-case time complexity of linear search is O(n).
Space Complexity
• In Linear Search, we are creating a boolean variable to store if the
element to be searched is present or not.
• The variable is initialized to false and if the element is found, the
variable is set to true.
• This variable can be used in other processes or returned by the
function.
• As the amount of extra data in Linear Search is fixed, the Space
Complexity is O(1).
• Step1 : Begin with the leftmost element of arr[] and one by one
compare x with each element.
• Step 3: If x does not match with any of the elements then return -1.
Program
Output