

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Implementing block search in JavaScript
Block Search
Just like Binary Search, Block Search is also a searching algorithm for sorted arrays. The basic idea is to check fewer elements (than linear search) by jumping ahead by fixed steps or skipping some elements in place of searching all elements.
For example
Suppose we have an array arr of length n and block (to be jumped) of size m. Then we search at the indexes arr[0], arr[m], arr[2 * m], ..., arr[k * m] and so on.
Once we find the interval arr[k * m] < x < arr[(k+1) * m], we perform a linear search operation from the index k * m to find the element x.
The time complexity of this algorithm is −
O(√n)
Example
Following is the code −
const arr = [1, 4, 6, 7, 9, 12, 15, 16, 17, 23, 25, 26, 27, 31]; const target = 25; const blockSearch = (arr = [], target) => { let { length: len } = arr; let step = Math.floor(Math.sqrt(len)); let blockStart = 0 let currentStep = step; while (arr[Math.min(currentStep, len) - 1] < target) { blockStart = currentStep; currentStep += step; if (blockStart >= len) return -1; } while (arr[blockStart] < target){ blockStart++; if (blockStart == Math.min(currentStep, len)) return -1; } if (arr[blockStart] == target) return blockStart else return -1; }; console.log(blockSearch(arr, target));
Output
Following is the output on console −
10
- Related Questions & Answers
- Implementing Linear Search in JavaScript
- Implementing a Binary Search Tree in JavaScript
- Implementing Priority Sort in JavaScript
- Implementing counting sort in JavaScript
- Implementing binary search in JavaScript to return the index if the searched number exist
- Block Scoping in JavaScript.
- Implementing the Array.prototype.lastIndexOf() function in JavaScript
- Implementing circular queue ring buffer in JavaScript
- Implementing Heap Sort using vanilla JavaScript
- Does JavaScript support block scope?
- Implementing incremental search and display the values with a specific number in MySQL?
- Implementing custom function like String.prototype.split() function in JavaScript
- Interpolation Search in JavaScript
- What is a block statement in JavaScript?
- How to label a block in JavaScript?
Advertisements