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.
Auf dieser Seite können Sie das Online-Video Divide by 2 using BIT SHIFTING in JavaScript | Binary search mit der Dauer stunde minuten sekunde in guter Qualität ansehen, das der Benutzer Mayank Srivastava 27 Juni 2024 hochgeladen hat, den Link mit Freunden und Bekannten teilen, dieses Video wurde auf Youtube bereits 451 Mal angesehen und es wurde von 26 den Zuschauern gefallen. Viel Spaß beim Betrachtenden Zuschauern gefallen!