Is there any way to write this in a way that would work for both dense and sparse arrays?  I only see a relatively small number of lines that are specifically about sparse arrays, and a lot that's just about the general idea, but maybe it's too difficult to separate the two.