Detect Order Changes in a List

algorithms

Let's say you have a list of values that are:

  1. a
  2. b
  3. c
  4. d
  5. e

The order on the list might be changed.

  1. a
  2. c
  3. d
  4. b
  5. e

How would you detect this change? We needed something like this when we were building a revision history page for our online form building tool. We found a quick and dirty solution, but I am looking for a more elegant solution for this. Here is what the revision descriptions look like:

jotform revisions page

Here is the tough part: Elements can be removed/added from/to anywhere on the list. So, the algorithm should be able to ignore those changes.

Best Answer

There are two approaches:

  1. Try to find a way to apply the diff algorithm to your model. This gets easier when there is a underlying textual representation (e.g. HTML source or another DSL).
  2. Don't have your form builder emit complete states, only have it emit differences which you can easily log. Instead of having the before and after lists, you'd log the “move field from x to y” operation.
Related Topic