"Day 17: Mastering Linear & Binary Search in Python"

Day 17 of My 45-Day Python & DSA Journey Topic: Searching Algorithms – Linear Search & Binary Search Today, I explored one of the most important problem-solving areas in DSA — searching algorithms, which help find elements efficiently from a list or array. 🔹 What I Learned: Linear Search The simplest search method — check every element one by one until the target is found. def linear_search(arr, key): for i in range(len(arr)): if arr[i] == key: return i return -1 nums = [10, 20, 30, 40, 50] print(linear_search(nums, 30)) # Output: 2 Time Complexity: O(n) Works on unsorted data. Binary Search A much faster method — repeatedly divide the search space by half. def binary_search(arr, key): low, high = 0, len(arr) - 1 while low <= high: mid = (low + high) // 2 if arr[mid] == key: return mid elif arr[mid] < key: low = mid + 1 else: high = mid - 1 return -1 nums = [10, 20, 30, 40, 50] print(binary_search(nums, 40)) # Output: 3 Time Complexity: O(log n) Works only on sorted data. Reflection: Today’s lesson made me realize the importance of choosing the right approach. While Linear Search is simple, Binary Search saves time exponentially for large datasets — a great example of algorithmic efficiency. Key Takeaway: “Efficiency is not just about speed; it’s about the smart use of logic.” 🔜 Next: I’ll move on to Sorting Algorithms — Bubble Sort, Selection Sort, and Insertion Sort, the building blocks for understanding algorithm design. #Python #DSA #SearchingAlgorithms #BinarySearch #LinearSearch #CodingJourney #LearningInPublic #CodeEveryday

To view or add a comment, sign in

Explore content categories