2

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?

3
  • I'm not sure how this is different than a priority queue implemented as a singly or doubly linked list, with integers as the "order" property. Is there some constraint that makes your situation unique? Commented Jun 25, 2009 at 7:27
  • 1
    Is the sort order required to be stored in DB (per user)? Commented Jun 25, 2009 at 8:01
  • Yes, the sort order will be stored in the DB for each object (1 object == 1 row in the db). Commented Jun 25, 2009 at 8:04

3 Answers 3

1

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 ...

Sign up to request clarification or add additional context in comments.

1 Comment

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

Linked list (doubly)?

3 Comments

Comparisons wouldn't be linear then. I'd have to potentially scan through the remainder of the list to figure out if a > b.
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.
Err -- or rather, they would be linear. Typo.
1

I don't think you can 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".

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.