I am trying to figure out the complexity of the function below. I am guessing it would be O(n), because the Random class produces a random number in O(1) and put() and containsKey() are also O(1).
But since there is a do-while inside the loop, I wasn’t sure if the complexity would change since random() could be called multiple times if the value is contained in the HashMap. I would appreciate any help!
HashMap<Integer, Integer> values = new HashMap();
for(int i=0 ; i<a.length; i++){
do{
// set variable random to some integer between 0 and a.length using Random class in Java, 0 is included.
}while(values.containsKey(random) == true);
b[i] = a[random]
values.put(random,0);
}
The length of the array is around 1000 and the random number generated is anywhere from 0 to 999.
1 Answer