Reputation: 2100
I have an array of integers. The integers can be positive or negative, and there can be duplicates. I sort the array, low to high, using qsort.
int myArray[] = { -4, -2, 0, 1, 1, 3, 3, 3, 9, 14, 17, 24 };
I then want to find the relative position of one of the integers (X) in the array, so I divide the position (Y) of the integer by the size of the array (S), and subtract .5 from the result, so that the relative position is expressed on a scale from -.50 to .50.
double position = Y/S - .50;
I want the lowest value in the array (in this case, -4) to be -.50, and the highest value (in this case, 24) to be .50? This works for the lowest value in the array, but not the highest:
double lowPosition = 0/12 - .50; // lowPosition = -.50 double
highPosition = 11/12 - .50; // highPosition = .42
Two questions:
What is the correct way to calculate this so I end up with the low value equal to -.5 and the high value = .5?
How can I accurately calculate the relative position of a value when there are duplicates? Should I eliminate the duplicates and then use the same calculation (position/size - .5)?
Upvotes: 0
Views: 373
Reputation: 16243
1) What is the correct way to calculate this so I end up with the low value equal to -.5 and the high value = .5?
Since the highest position in an array is at S - 1
(where S
is the size of the array), you'll have to divide by S - 1
instead of S
.
Make sure to have a special case for arrays of size 1
, or you'll get a division by 0
.
2) How can I accurately calculate the relative position of a value when there are duplicates? Should I eliminate the duplicates and then use the same calculation (position/size - .5)?
It depends what relative positions you want to get. But removing duplicates sounds like a reasonable approach.
Upvotes: 1