Algorithms Day 1- Linear and Binary Search
Daniel
Posted on April 17, 2020
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
Posted on April 17, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.