Marceau
Marceau

Reputation: 1703

Data structure for random access linked list

I have a need for a data structure that will be able to give preceding and following neighbors for a given int that is part of the structure.

Some criteria I've set for myself:

This is in Java, and is mostly theoretical, as I've started using the solution described below.

Things I've considered:

What I'm using now is a combination of int[] and HashMap:

What I like:

What I dislike:

I'd be curious to hear of better solutions.

Upvotes: 3

Views: 1322

Answers (2)

MadConan
MadConan

Reputation: 3767

ints are ordered externally, that order will most likely not be a natural ordering, and that order must be preserved (ie. there is no contract whatsoever regarding the difference in value between two neighboring ints).

This says "Tree" to me. Like Aaron said, expensive insert but efficient lookup, which is what you want if you have write once, read many.

EDIT: Thinking about this a bit more, if a value can only ever have one child and one parent, and given all your other requirements, I think ArrayList will work just fine. It's simple and very fast, even though it's O(n). But if the data set grows, you'll probably be better off using a Map-List combo.

Keep in mind when working with these structures that the theoretical performance in terms of O() doesn't always correspond to real-word performance. You need to take into account your dataset size and overall environment. One example: ArrayList and HashMap. In theory, List is O(n) for unsorted lookup, while Map is O(1). However, there's a lot of overhead in creating and managing entries for a map, which actually gives worse performance on smaller sets than a List.

Since you say you don't have to worry about memory, I'd stay away from array. The complexity of managing the size isn't worth it on your specified data set size.

Upvotes: 0

Aaron Digulla
Aaron Digulla

Reputation: 328604

One solution is to sort the array when you add elements. That way, the previous element is always i-1 and to locate a value, you can use a binary search which is O(log(N)).

The next obvious candidate is a balanced binary tree. For this structure, insert is somewhat expensive but lookup is again O(log(N)).

If the values aren't 32bit, then you can make the lookup faster by having a second array where each value is the index in the first and the index is the value you're looking for.

More options: You could look at bit sets but that again depends on the range which the values can have.

Commons Lang has a hash map which uses primitive int as keys: http://grepcode.com/file/repo1.maven.org/maven2/commons-lang/commons-lang/2.6/org/apache/commons/lang/IntHashMap.java but the type is internal, so you'd have to copy the code to use it.

That means you don't need to autobox anything (unboxing is cheap).

Related:

Upvotes: 1

Related Questions