I have an array, A, of length n. Let B be an array (that we never want to store separately - this is just to help explain) containing every k'th element of A. I want to find the median of B, and I want to move that element of A to the floor(n/2)'th position in A.
How can I do this efficiently? I'm thinking of trying to make a single call to std::nth_element, passing a pointer to A. However, I need this pointer to increment by k elements of A. How do I do this? Essentially:
A2 = (kFloat *)A;
std::nth_element(A2, A2 + (n/k)/2, A2 + (n/k));
swap(A[ ((n/k)/2)*k ], A[n/2]); // This might be redundant
where kFloat would be a structure that acts like a float, but when you increment the pointer it moves k*sizeof(float) in memory.
Note: I do not require the true median (average of middle two when n is even).
Edit: Another way of saying what I want (doesn't compile, because k is not a constant):
std::nth_element((float[k] * )A, ((float[k] * ) A)[(n / k) / 2], ((float[k] * ) A)[n / k]);
Edit 2: I am changing algorithm.cc, so I don't want to introduce dependencies on a library like Boost. I would like to use core C++11 functionality + std only.
For anyone else who has this problem in the future, I've modified some functions from algorithm.cc to include a stride parameter. Many of them assume that _First and _Last span a multiple of your stride, so I don't recommend calling them. However, you can call the following function:
To call this function, you need to include this header:
An example of using this function: