Question

I am having trouble figuring out what the code segment below is doing. It is taken from the book Realistic Image Synthesis Using Photon Mapping by Henrik Wann Jensen. I think what it's trying to do (or what I think it should be trying to do given its place in the code) is compute the median index in an array between some start and end index.

// inputs are an array, start and end indices that define a subset of the array
int median = 1;
while((4*median) <= (end-start+1))
  median += median;

if ((3*median) <= (end - start + 1)) {
   median += median;
   median += start - 1;
} else
  median = end - median + 1

For more context, the code comes from a section that builds a kd-tree data structure given a list of 3D points. At each recursive step of building the kd-tree the median point (with respect to some dimension) is selected to be the root of a new kd-tree.

I think this code is supposed to compute the median index between some start and end index but if I'm correct then I can't figure out why this median index is computed in such a weird way.

Any help or insight would be appreciated, thanks!

Edit: Thanks to Vaughn Cato I now see that it is necessary to compute the median index in this way. Originally I was confused as to why you couldn't just do (end - start)/2 + start. The goal of this code is to take a list of points and convert it into a full, balanced kd-tree that could be stored in a heap like data structure (the whole binary tree in an array). Computing the median index in the naive way won't necessarily get you a tree that you can flatten into array.

Now I'm confused as to how somebody came up with that. Can anybody either explain or point me in the direction of a derrivation?

Was it helpful?

Solution

The resulting median value is always a power of two away from the start or end. Assuming the median value is used to partition the tree, this would lead to branches that are powers of two in size, meaning each node would have either two or zero children. This could provide some efficiency in traversing the leaves of the tree.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top