π Day 51/150 – Linear Search in Python
Linear Search is one of the simplest searching techniques. It checks each element in the list one by one until the target value is found.
Best for small or unsorted data
Easy to understand and implement
Let’s explore different methods π
πΉ Method 1 – Using for Loop
numbers = [10, 20, 30, 40, 50] target = 30 found = False for num in numbers: if num == target: found = True break print("Found" if found else "Not Found")
✅ Simple and clean approach
πΉ Method 2 – Using while Loop
numbers = [10, 20, 30, 40, 50] target = 25 i = 0 found = False while i < len(numbers): if numbers[i] == target: found = True break i += 1 print("Found" if found else "Not Found")
πΉ Method 3 – Using Loop with else
numbers = [10, 20, 30, 40, 50] target = 20 for num in numbers: if num == target: print("Found") break else:
print("Not Found")
✅ else runs only if loop completes without break
πΉ Method 4 – Using Function
def linear_search(arr, target): for i, value in enumerate(arr): if value == target: return i return -1 result = linear_search([10, 20, 30, 40], 30) if result != -1: print("Found at index:", result) else: print("Not Found")


0 Comments:
Post a Comment