Divide by 2 using BIT SHIFTING in JavaScript | Binary search

Publicado em: 27 Junho 2024
no canal de: Mayank Srivastava
451
26

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.


Nesta página do site você pode assistir ao vídeo on-line Divide by 2 using BIT SHIFTING in JavaScript | Binary search duração hora minuto segundo em boa qualidade , que foi baixado pelo usuário Mayank Srivastava 27 Junho 2024, compartilhe o link com seus amigos e conhecidos, no youtube este vídeo já foi visto 451 vezes e gostou 26 espectadores. Boa visualização!