Sorting a list without a counter

This is currently just conseptual, but it bothers my brain.

If I have a list of items - in my mind it's a HTML/JS implementation, but that's just because I'm a visual thinker ;)

I want to use drag and drop to sort this list, with the aim of storing the new order when I'm done. Is there a way to do this without numbering the items, and then updating the number of the dropped item + every single item that follows it? Isn't that very inefficient?

Upvotes: 0

Views: 86

Answers (4)

Debanjan Basu
Debanjan Basu

Reputation: 894

Not including any code here, because this is a conceptual question.
You have to have a number for every element in the list anyway, since they have to have a Total Ordering among themselves to be represented as a list.
If you don't expect the number of elements in the list to be large, a Bubble Sort should work very well for you.

Upvotes: 0

Jørgen R
Jørgen R

Reputation: 10806

I would recommend using a JavaScript framework to do the job.

KnockoutJS should fit your needs (from the website):

Knockout is a JavaScript library that helps you to create rich, responsive display and editor user interfaces with a clean underlying data model. Any time you have sections of UI that update dynamically (e.g., changing depending on the user’s actions or when an external data source changes), KO can help you implement it more simply and maintainably.

Upvotes: 1

pablochan
pablochan

Reputation: 5715

As far as performance goes, changing the numbering of the elements is nothing next to actually rendering the transition (while you're dragging an element), so no, it's not inefficient.

You can use a doubly linked list in order to minmize the amount of operations needed to change the order of the collection.

Upvotes: 3

wrhall
wrhall

Reputation: 1308

If you left gaps in the numbers, you could probably do it efficiently -- for instance, let the first element be 10, the second be 20, the third 30, etc. Then when you drag something in front of the second one and after the first, call it 15 (or something).

Rather than incrementing numbers every time, you'd only have to do it if you ran out of space. At the end, you could just order the objects by lowest number.

Upvotes: 0

Related Questions