>> operator in C++

Hello,
What is this and why do we use it in our code?


1
2
3
4
5
6
7
8
9
void MergeSortHelper(int arr[], int lo, int hi) {
	int mid;
	if (lo < hi) {
		mid = (lo + hi) >> 1;
		MergeSortHelper(arr, lo, mid);
		MergeSortHelper(arr, mid + 1, hi);
		Merger(arr, lo, mid, hi);
	}
}
Last edited on
In this case, it means "bitshift to right this many bits".

Take a binary number:

0011 0000

Bitshift it to the right by 1 bit ( >> 1 )

Now it's 0001 1000


There once was a time when bit-twiddlers did this because bit-shifting something one bit to the right is the same as dividing it by two, but was faster.

With modern compilers those days are long gone,

What this code is actually trying to do is find the mid-point between lo and hi

Take out mid = (lo + hi) >> 1; and in its place write mid = (lo + hi) / 2;
Last edited on
Used in this context it shifts all the bits of the binary representation of a number by one place to the right. So it effectively divides an integer by 2.

That line does the same as
mid = (lo + hi)/2;
Topic archived. No new replies allowed.