views:

62

answers:

2

If I define my own comparator for the generic HashSet<T> in System.Collections.Generic, and its runtime is O(1), is the lookup time of the hashset still O(1)?

I would think no just because there doesn't appear to be a way to set the comparator.

+3  A: 

The reason that the lookup time of a regular hashset is O(1) is because it uses open addressing to place objects into the array, so that won't change even if you use your own comparator.

codersarepeople
Wait a minute there. Suppose that the default hash generated is based on the object pointer itself, and that my comparer says that two things are equal solely based on whether two objects are shallowly equal (rather than if they point to the same object.) How would the hash work in this case?
+1  A: 

In its best case it will have a insertion of amortised O(1) and a lookup of O(1).

In its worse case it will have an insertion of amortised O(n) and a lookup of O(n).

A good comparator will help keep the real case closer to the best case than the worse, by having a good hash method.

A bad comparator will, well be bad. (Write a deliberately bad comparator that returns the same value for every hashcode [valid, but pointless] and you will be able to see this O(n) behaviour).

A good comparator can get unlucky, but for the most part the real cases are close enough to O(1) that we can think of it as O(1) and not be steered to far away.

Edit:

Missed the bit about "there being no way to set the comparator". There is, HashSet has a constructor that takes one.

Jon Hanna
Thanks, didn't see that about the constructor.
You could get much worse than O(n) if the execution time for your comparator is of significantly higher order.
Slartibartfast