⬅ Previous Topic
Move Zeroes in Array to EndNext Topic ⮕
Union of Two Arrays⬅ Previous Topic
Move Zeroes in Array to EndNext Topic ⮕
Union of Two ArraysTopic Contents
Given an array of integers and a target value called key
, your task is to search for the key in the array using linear search.
-1
.This is the simplest and most intuitive way to search for a value in an array.
arr
and a target key
.0
to n-1
.arr[i] == key
.i
.-1
.def linear_search(arr, key):
for i in range(len(arr)):
if arr[i] == key:
return i
return -1
# Sample Input
arr = [10, 20, 30, 40, 50]
key = 30
print("Element found at index:", linear_search(arr, key))
Case | Time Complexity | Explanation |
---|---|---|
Best Case | O(1) | The target element is found at the very first index of the array. |
Average Case | O(n) | On average, the search will check half of the array before finding the target or confirming it doesn't exist. |
Average Case | O(n) | In the worst case, the algorithm will check every element in the array, either finding the target at the end or not finding it at all. |
O(1)
Explanation: The algorithm uses a constant amount of extra space—just a loop variable and the target value—regardless of the array size.
We are performing a linear search for the value 40
in the array.
Compare arr[0] = 10
with key = 40
.
No match. Continue to next index.
Compare arr[1] = 20
with key = 40
.
No match. Continue to next index.
Compare arr[2] = 30
with key = 40
.
No match. Continue to next index.
Compare arr[3] = 40
with key = 40
.
Match found! Element 40
is equal to key 40
. Return index 3
.
⬅ Previous Topic
Move Zeroes in Array to EndNext Topic ⮕
Union of Two ArraysYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.