Hey friends!
I'm late today again๐. I'm almost done with the two full-stack apps I'm building, so I'll be on time next week.
Check them out on my Github if you're curious :)
Itโs another tutorial Wednesday, and today weโre stepping into the world of Data Structures & Algorithms (DSA). Donโt worry, it sounds fancy but weโll keep it simple and fun ๐.
Weโll start with one of the most basic (but powerful) search algorithms: Linear Search.
๐ค What is Linear Search?
Linear search is like checking through a shopping list one item at a time:
- You look at the first item โ if itโs not what you want, move to the next.
- Repeat until you find it (or reach the end).
Simple! No shortcuts. Just checking one by one.
How Linear Search Works in Code
function linearSearch(arr, target) {
for (let i = 0; i < arr.length; i++) {
if (arr[i] === target) {
return i; // found at index i
}
}
return -1; // not found
}
// Example:
const items = [10, 20, 30, 40];
console.log(linearSearch(items, 30)); // 2
console.log(linearSearch(items, 50)); // -1
โฑ๏ธ Time Complexity
- Best case: O(1) โ target is at the start.
- Worst case: O(n) โ target is at the end or not present.
Think of it like searching your name on an attendance list. If youโre the first name, lucky! Otherwise, you might have to go through the whole list.
Try It Yourself (Interactive Demo)
I built a small playground where you can:
- Enter an array
- Enter a number to search
- See if itโs found (and where)
๐๐ฝโโ๏ธ Over to You!
Linear Search is simple but forms the foundation of searching algorithms. Next time, we can explore faster ones (like Binary Search).
But before then โ
๐ Can you try writing your own version of Linear Search using a while
loop instead of a for
loop?
Let me know if you do the challenge! I'd like to see yours! Connect with me on GitHub
Was this tutorial helpful? Got questions? Or any insight to help me write better tutorials? Let me know in the ๐ฌ!
Thatโs it for todayโs midweek mini tutorial!
Iโm keeping things light, fun and useful; one small project at a time.
If you enjoyed this, leave a ๐ฌ or ๐งก to let me know.
And if youโve got an idea for something you'd like me to try out next Wednesday, drop it in the comments. ๐
Follow me to see more straight-forward and short tutorials like this :)
If you are curious about what I do, check out my Portfolio
:-)
Web trails
You can also find me here on LinkedIn
or here X (Twitter)
โ๐พ Iโm documenting my learning loudly every Wednesday. Follow along if you're learning JavaScript too!
Letโs keep learning together!
See you next Wednesday ๐
Top comments (0)