views:

56

answers:

3

I have a list of ordered objects stored in the database and accessed through an ORM (specifically, Django's ORM). The list is sorted arbitrarily by the user and I need some way to keep track of it. To that end, each object has an "order" property that specifies its order in relation to the other objects.

Any data structure I use to sort on this order field will have to be recreated upon the request, so creation has to be cheap. I will often use comparisons between multiple objects. And insertions can't require me to update every single row in the database.

What data structure should I use?

A: 

Linked list (doubly)?

shahkalpesh
Comparisons wouldn't be linear then. I'd have to potentially scan through the remainder of the list to figure out if a > b.
Zain
Insertions and deletions into an ordered linked list is linear time, a.k.a O(N). There is an upper bound of N iterations to find the value you are looking for.
Jeff Meatball Yang
Err -- or rather, they *would* be linear. Typo.
Zain
+1  A: 

Heap

As implemented by std::set (c++) with comparison on the value (depends on the value stored), e.g. integers by value, strings by string ordering and so on. Good for ordering and access but not sure when you need to do reordering, is that during insertion, constantly and so on.

You're not specifying what other constraints do you have. If number of elements is know and it is reasonable or possible to keep fixed array in memory then each position would be specified by index. Assumes fixed number of elements.

You did not specify if you want operations you want to perform often. If you load up values once then access them without modification you can use one algorithm for creation then either build index or transform storage to be able to use fast access ...

stefanB
Thanks, stefanB. I added some more info to my post. Sorry, still new here :)
Zain
A: 

I don't think you cannot get constant time for insertions (but maybe amortized constant time?).

I would use a binary tree, then the bit sequence describing the path can be used as your "order property".

starblue