DEV Community

Daniel
Daniel

Posted on

Algorithms Day 1- Linear and Binary Search

So Along with the 100daysofcode challenge, I started to practice algorithms and data structures. So this is my first post about it

Linear Search

  • Linear Search is one of the common practices that we use almost every time to search inside an array.

  • Just loop through the Array and find the match simple. That's a linear search.

Linear Search - Pseudocode

  • Create a function that accepts an array and a value to be searched.

  • Loop through the array and check the condition if the current element of the iteration is equal to the value to be checked. If found return the index. Else return - 1

  • The code is mentioned below

Binary Search

  • It's faster compared with the linear search method. Rather than comparing and eliminating one by one we can eliminate half of the array elements in a single time

  • But it only works on sorted arrays. It takes two inputs a sorted array and the value to be searched.

Binary Search - Pseudocode

  • Create a function that accepts a sorted array and the value to be searched.

  • Create start pointer and ending pointer. When the start pointer is less than the ending pointer. Create a pointer between the two.

  • If the value in the middle is smaller in comparison move the start pointer over the middle pointer.

  • If it's smaller move the ending pointer down to the middle pointer

  • Return the index.

  • The code is mentioned below

I believe that's it. Thanks for reading will keep you guys posted

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay