Algorithm Steps
- Given an array
arr
and a targetkey
. - Iterate through the array from index
0
ton-1
. - For each element, check if
arr[i] == key
. - If a match is found, return the index
i
. - If no match is found after the loop ends, return
-1
.
Linear Search in Array - Optimal Approach Code
Python
JavaScript
Java
C++
C
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))
Detailed Step by Step Example
We are performing a linear search for the value 40
in the array.
{
"array": [10,20,30,40,50],
"showIndices": true
}
{
"array": ["key:", 40],
"emptyIndices": [0],
"highlightIndicesGreen": [1]
}
Check index 0
Compare arr[0] = 10
with key = 40
.
{
"array": [10,20,30,40,50],
"showIndices": true,
"highlightIndices": [0],
"labels": {"0":"i"}
}
No match. Continue to next index.
Check index 1
Compare arr[1] = 20
with key = 40
.
{
"array": [10,20,30,40,50],
"showIndices": true,
"highlightIndices": [1],
"labels": {"1":"i"}
}
No match. Continue to next index.
Check index 2
Compare arr[2] = 30
with key = 40
.
{
"array": [10,20,30,40,50],
"showIndices": true,
"highlightIndices": [2],
"labels": {"2":"i"}
}
No match. Continue to next index.
Check index 3
Compare arr[3] = 40
with key = 40
.
Match found! Element 40
is equal to key 40
. Return index 3
.
{
"array": [10,20,30,40,50],
"showIndices": true,
"highlightIndicesGreen": [3],
"labels": {"3":"i"}
}