While performing binary search you must have come across the logic where you had to calculate the half of the length of the array. To implement it programmers usually write the following code where they first find out if the length of the array is odd or even by taking modulus of the length by2 and if the remainder is 0 they simply divide it by 2 and if it is 1 they take the floor value of the resulting decimal. But what if I tell you there is a quick and easy way to calculate the half of any value be it odd or even by just using a single operator and without the need of the floor method. The operator is the bitwise right shift operator and if you bit shift a number to the right by 1 position it effectively divides the number by 2. Lets try it out out by bit shifting the number 8 by 1 position. Now 8 can be represented as 1 0 0 0 in binary and you right shift the bits by a single position you are left with 0 1 0 0 which is the binary equivalent of 4. Let's also right shift an odd number like 9 which which again results to 4. Hence this also proves that bit shifting in JS rounds down. So now we can successfully replace this conditional by a single operator.
Sur cette page du site, vous pouvez voir la vidéo en ligne Divide by 2 using BIT SHIFTING in JavaScript | Binary search durée heure minute seconde en bonne qualité , qui a été Téléchargé par l'utilisateur Mayank Srivastava 27 juin 2024, Partagez le lien avec vos amis et connaissances, sur youtube cette vidéo a déjà été regardée 451 fois et il a aimé 26 téléspectateurs. Bon visionnage!