2

I'm studying some common algorithms implementations in JavaScript, and found this one while looking for quicksort: https://rawgit.com/escherba/algorithms-in-javascript/master/src/quickmiddle-sort.js

It implements an array partition function as well:

function partition(array, left, right) {
        var pivot = array[(left + right) >>> 1];
        while (left <= right) {
            while (array[left] < pivot) { left++; }
            while (array[right] > pivot) { right--; }
            if (left <= right) {
                var temp = array[left];
                array[left++] = array[right];
                array[right--] = temp;
            }
        }
        return left;
}

I wonder what is the math behind the bitwise operation, I'm quite a newbie with them.

MattSom
  • 2,097
  • 5
  • 31
  • 53

3 Answers3

2

shift right by 1 is exactly like divide by 2 you can test it by yourself . right a number in a binary and do a right shift and check the result

Mero
  • 622
  • 12
  • 24
  • Ah, I see. So basically we avoid the usage of a division function to be faster? – MattSom Mar 23 '17 at 11:04
  • 1
    Yes 4 in binary is 100 shift right you loose the 0 the least significant bit so we end up with 10 binary which is 2 decimal :) it's faster that normal division – Mero Mar 23 '17 at 11:38
2

Suppose, you are asking about this part

(left + right) >>> 1

There is an addition of two operands and a zero-fill shift right >>> operator with one bit.

For example you have the value 9 and shift one bit to right.

      9 (base 10): 00000000000000000000000000001001 (base 2)
                   --------------------------------
9 >>> 1 (base 10): 00000000000000000000000000000100 (base 2) = 4 (base 10)

The result is an integer number of 4.

Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

Bitwise operation is nothing but dividing the sum of left and right values by 2. if left=2 and right=7 output is 9/2 and truncated to 4.

rathna
  • 1,055
  • 2
  • 11
  • 23