How To Do Binary Search In Javascript | Binary Search - letsbug

   Binary Search is one of the most important searching algorithm and today's article is on it.  Binary search is a quicker method to search than linear search. But it cannot be applied to unsorted data structures. The binary search is based on the approach divide-and-conquer. 

Binary Search In Javascript

    The binary search starts by testing the data in the middle element of the array. This determines target is whether in the first half or second half. If target is in first half, we do not need to check the second half and if it is in second half no need to check in first half.

    And similarly we repeat this process until we find target in the list or not found from the list. Here we need 3 variable to identify first, last and middle element. This algorithm can be Iterative or recursive.

Below is the code of binary search in javascript.

/**
 *
 * @param {Array<Number>} arr is array
 * @param {Number} x
 * is the element to find in array arr
 * @returns {Number} the position of element in arr
 */
function binarySearch(arr, x) {
    let low = 0
    let high = arr.length - 1
    let mid
    while (low <= high) {
        mid = Math.floor((low + high) / 2);
        if (arr[mid] < x) {
            low = mid + 1
        } else if (arr[mid] > x) {
            high = mid - 1
        } else {
            return mid
        }
    }
    return -1
}

let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
let result = binarySearch(arr, 4)
console.log(result)

    In the above code in the binarySearch function we start by first initializing 3 three variables which are low, high and mid. And as this is a iterative example so we then use while loop to iterate over the loop.

    While low <= high we set the mid variable to the middle of the array. And then using if checks we determine weather the element is in the first half or not and accordingly change the value of low and high variable. 

    This logic is not limited to one language you can use this logic and impliment binary search in any programming langauage you preffer.

Thankyou

Comments

Categories

Big Data Analytics Binary Search Binary Search Tree Binary To Decimal binary tree Breadth First Search Bubble sort C Programming c++ Chemical Reaction and equation class 10 class 10th Class 9 Climate Complex Numbers computer network counting sort CSS Cyber Offenses Cyber Security Cyberstalking Data Science Data Structures Decimal To Binary Development diamond pattern Digital Marketing dust of snow Economics Economics Lesson 4 Email Validation English fire and ice Food Security in India Footprints Without feet Forest And Wildlife Resources game Geography Geography lesson 6 glassmorphism Glossary Graph HackerRank Solution hindi HTML image previewer India-Size And Location Insertion Sort Internet Network Status Interview Questions Introduction to cyber crime and cyber security IT javascript tricks json to CSV converter lesson 2 lesson 1 lesson 2 Lesson 3 Lesson 6 lesson 7 Life lines of National Economy life processes Linear Search Linked List lowest common ancestor Machine Learning MCQs median in array Merge sort min and max of two numbers Moment Money and Credit My Childhood Natural Vegetation and Wildlife NCERT Network connectivity devices Network Models Network Security No Men Are foreign Node.js operator overloading P5.js PHP Physical features of India Population Prime Numbers python Quick sort R language Rain on the roof Regular Expression Resources and development reversing array saakhi science Searching Algorithm Selection sort Social Media Marketing social science Software Engineering Software Testing Sorting Algorithm Stacks staircase pattern System Concepts Text Recognition The last Leaf time converter Time Passed From A Date Todo List App Tree Trending Technologies Understanding Economic Development username and password video player Visualization water resources Wired And Wireless LAN साखी
Show more

Popular Posts

Big Data MCQs(multiple choice questions) with answers - letsbug

Digital Marketing MCQ(Multiple Choice Questions) with Answers | part 1 | letsbug

Software Engineering MCQs questions with answers - letsbug