views:

236

answers:

3

What is the best data structure (container) for fast element insertion/deletion by index?

+1  A: 

Depends on whether or not you're talking about something in memory or on disk. Usually, on disk it is some variant of a B-tree, and usually, in memory, it is generally a linked list (if you know what node you need to insert at).

Dave Markle
linked list is no good since I don't know the node (there is "access by index" requirement which takes O(n) for a list)
nnd
+1  A: 

Try a hash table that dynamically resizes at fixed intervals.

Assuming a pretty good uniform distribution, you should have basically constant time [O(1)] access time.

http://www.cs.cornell.edu/courses/cs312/2006fa/lectures/lec14.html

That link seems to give a good explanation.

Isaac Hodes
I've updated my answer – I think this is a good solution.
Isaac Hodes
+1  A: 

You could get O(log n) performance using a binary tree with a node structure like this:

struct Node<T>
    T value
    Node left
    int left_count
    Node right
    int right_count
end

The left_count value would hold the number of nodes in the left branch of the tree, and similarly for the right side. Lookup would be performed by starting at the top of the tree and traversing downward based on comparing the desired index value with the left and right counts. Insertion and deletion would be performed using the normal binary tree algorithms, with appropriate adjustment to the count values. More consistent performance can be achieved by requiring that the binary tree is balanced.

This kind of tree probably has a name; more information appreciated!

Greg Hewgill
I guess you mean Red-black tree
nnd
A red-black tree doesn't contain the left and right subtree counts.
Greg Hewgill