O (log (n)) approach (this is torn directly from the answer to a very similar question ):
The usual method is to convert the array to an array of sums:
[10 60 5 25] --> [10 70 75 100]
Select a random number in the range from zero to the total (in the example: 0 <= x < 100 ). Then use bisection in the cumulative array to find the index in the original array:
Random variable x Index in the Cumulative Array Value in Original Array ----------------- ----------------------------- ---------------------- 0 <= x < 10 0 10 10 <= x < 70 1 60 70 <= x < 75 2 5 75 <= x < 100 3 25
For example, if the random variable x is 4, then halving the cumulative array gives a position index of 0, which corresponds to 10 in the original array.
And, if the random variable x is 72, halving the cumulative array gives an index of position 2, which corresponds to 5 in the original array.
source share