EDIT: I'm not sure that my original question is clear enough. I need an algorithm that will compute the minimal sequence of moves to rearrange an array from one order to another. It is known that both arrays will contain the same elements (no duplicates) and have the same length. For example:
reorder(
['d', 'a', 'c', 'b', 'e'],
['a', 'b', 'c', 'd', 'e']
)
should return something like:
[
{move:'d', after:'b'},
{move:'c', after:'b'}
]
which indicates that I should first move the element 'd' to after 'b', then move 'c' to after 'b' and the array will be in the desired order.
Background: I'm working on a project (moving most of the functionality in rtgui to the client-side, actually). Right now I'm working on sorting. Basically I have a list of divs that I want sorted in some arbitrary order. I can get the desired order as follows:
var hashes = {
before: [],
after: [],
};
var els = $('div.interesting-class').toArray();
var len = els.length;
for(var i = 0; i < len; i++) hashes.before.push(els[i].id);
els.sort(getSortComparator());
for(var i = 0; i < len; i++) hashes.after.push(els[i].id);
Now hashes.before
and hashes.after
contain the unordered and ordered lists of element IDs. When reordering the list, the most expensive operation, by far, is actually moving the DOM elements around. I had been doing this as follows:
var c = $('#container-id');
$(els).each(function() {
c.append(this);
});
This works, but is slower than necessary, since on average, only 2 or 3 elements really need to be moved. Therefore, I need an algorithm that will compute the minimal sequence of moves to rearrange an array from one order to another (in this case, operating on hashes.before
and hashes.after
). Can anyone suggest one or give any ideas?
I've tried several general-purpose "diff" algorithms so far, but they didn't really give me what I wanted. I think what I need is like that, but more specialized.