Smart way to calculate position in an array (C ++)
For performance in an O (n ^ 2) algorithm, I want to halve the complexity. Basically, I have the structure of this form:
0 1 2 3 4 5
----------------------
0 | 1
1, 2 | 2
3, 4, 5 | 3
6, 7, 8, 9 | 4
10, 11, 12, 13, 14 | 5
15, 16, 17, 18, 19, 20| 6
So I created a size vector ((1+n)*n/2)
- obviously an arithmetic sum. The point is that I now need to calculate each position forward and backward. As an example, if I want to calculate the position in the column 2
and row 5
, I can calculate it like this:
int get_position(int x, int y)
{
int smaller = min(x, y);
int greater = max(x, y);
return ((1 + greater) * greater / 2) - greater + smaller;
}
Question: how can I calculate it back? In other words, for example, from position No. 17
I would like to receive 2
and 6
.
Or maybe there is a better way to do this in C ++? (some structure will simplify)
EDIT I am looking for a way to calculate this in O (1). He exists?
source to share
This is not the square of N, as we can eliminate all arrays going down and search the correct array using the anchor points.
We first check the first number of each array and expect it to be between arri [0] and arri + 1 [0].
After that, you can use the Binary search algorithm to find the correct number in the array.
Binary search is log n and I can't apologize for the time it took for the first part, but I'm assuming log n. So this operation can be done in log n time
source to share