Searching in JavaScript

Searching in JavaScript

This is my first blog on hashcode ... I am excited but a little nervous. so let's get started.

In this blog, we understand step by step how to use the searching algorithm in javascript.

What is Searching?

Searching means to find a particular element is present in the array or not. If the element is present in the array, the searching is successful, and it returns the index or location of that element in the array.

They are different types of searching techniques, which will discuss in this blog.

  1. Linear Search
  2. Binary Search

Linear search is also called sequential search it's the very simplest method for searching an array for a particular element. ln, this type of searching technique we use the ordered or unordered list of elements (array in which data of elements are not sorted).

carbon (1).png

Now, we understand the above code in more depth how this searching has been performed.

Given array.. carbon.png

Step 1: search element 50 compared with the first element of the array i.e. 10

carbon.png Both are not matching. Move to the next element

Step 2. search element 50 compared with the next element of the array i.e. 9

carbon.png Both are not matching. Move to the next element

Step 3. Similarly, the above process is done with each element of the array. So, search element 50 compared with the next element of the array i.e. 50

carbon.png Both are matching. We stop the comparing and display the message

Given value have been found in the given array on index 5

Binary search is a searching algorithm that works efficiently with the sorted arrays. That means binary search is used only with a list of array elements that have been arranged in ascending or descending order. The binary can't be used for those arrays that are arranged in random order.

This search process starts with comparing the search element with the middle element in the list. If both are matched, display the message "element found". If an element is not found in the middle then we check search element is smaller or larger than the middle element. If the element is smaller, then we repeat the same process for the left element of the middle element. If the search element is larger, then we repeat the same process for the right element of the middle element.

I have done the binary search in two methods:-

1. using while,

2. using every

1. Using while

aaaaa.png

2. Using every

We use every() method it is just similar to forEach() method, except it stops iterating through the array whenever the callback function returns a falsy value.

carbon.png

Did you find this article valuable?

Support Swaraj Kumar by becoming a sponsor. Any amount is appreciated!