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.
On this page of the site you can watch the video online Divide by 2 using BIT SHIFTING in JavaScript | Binary search with a duration of hours minute second in good quality, which was uploaded by the user Mayank Srivastava 27 June 2024, share the link with friends and acquaintances, this video has already been watched 451 times on youtube and it was liked by 26 viewers. Enjoy your viewing!