Data Structures · Visualization
Search an Element
Array
Searching for a value in an unsorted array means checking each element one by one, from the first index to the last, until the value is found or the array runs out. Time: O(n) worst case (target absent or at the end), O(1) best case (first slot). Space: O(1).
Big-O: Random access O(1); insert/delete in the middle O(n).
Search an Element
ArraySearching for a value in an unsorted array means checking each element one by one, from the first index to the last, until the value is found or the array runs out. This straight-line scan is called linear search — there is no shortcut unless the array is sorted, because any element could be anywhere.
How Search an Element Works
- Start at index 0 and read the element stored there.
- Compare it with the target value you are looking for.
- If they match, return the current index and stop.
- If not, move one index to the right and compare again.
- If you pass the last element without a match, the value is not in the array (return -1).
Search an Element Worked Example
Input: Search for 30 in [10, 20, 30, 40]
- Compare arr[0] = 10 with 30 → no match
- Compare arr[1] = 20 with 30 → no match
- Compare arr[2] = 30 with 30 → match! Return index 2
Output: 30 found at index 2
Press ▶ Run to watch it step by step.
def linear_search(arr, target):
for i in range(len(arr)): # scan left → right
if arr[i] == target: # compare with target
return i # found: index i
return -1 # not found
a = [10, 20, 30, 40]
print(linear_search(a, 2)) # 2
# example: search for 30 on [10, 20, 30, 40]Behind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Search an Element Time & Space Complexity
When to Use Search an Element
- Looking up whether an ID or username already exists in a small list
- Finding the position of an item before updating or deleting it
- The fallback strategy whenever data is unsorted and small enough that sorting first is not worth it
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Ready for the next step?
See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.