Reservoir sampling is a randomized algorithm that is used to select out of samples; is usually very large or unknown. For example, reservoir sampling can be used to obtain a sample of size from a population of people with brown hair. This algorithm takes to select elements with uniform probability.
Copy the first elements from the input array to the output array.
Iterate from to (both inclusive). In each iteration :
2.1 Generate a random number from 0 to .
2.2 If is less than , replace the element at index in the output array with the item at index in the input array.