3 ms·
Good to see this interesting and very fundamental topic getting attention, and looking forward to the next post, where hopefully the algorithm's cleverness will
by akoboldfrying 3y ago
Good to see this interesting and very fundamental topic getting attention, and looking forward to the next post, where hopefully the algorithm's cleverness will be explored.
>It does this by being greedy, that is trying to consume as many lines that are the same before making a change (therefore avoiding the “wrong end” problem), and also by preferring deletions over insertions when given a choice, so that deletions appear first.
Not really. The algorithm guarantees to find an alignment/diff/edit script of minimal length, but whether it prefers the "leftmost" such alignment ("wrong-end" here and in many similar cases in source code) or the "rightmost" ("right-end" here) is not a crucial aspect of how it works. The preference can be switched by reversing both inputs before diffing and then reversing the output afterwards -- but that's also the case for any other algorithm that solves this problem optimally.
Myers's algorithm is greedy in another sense, however: It greedily hunts first for a solution in which no edits are necessary, then solutions in which 1 edit (insertion or deletion) is necessary, then 2, etc., terminating as soon as it finds a solution. Clearly this leads to an optimal (smallest-possible) diff. It also means that it takes time proportional to the amount of difference between the two inputs, which is the clever part: This is what makes it much faster than other approaches in the common case where the two inputs are highly similar.
- travisgriggs 3y agoIt was posted in 2017. You can get to part 2 from the link at the bottom.
- ynik 3y agoBut there's also the not-so-common (yet still somewhat frequent) case where the inputs are highly different. Myers diff alone would take quadratic time, which in practice is often unacceptable. Real-world implementations often have a limit on the amount of difference (e.g. max(256, sqrt(input size))), and if that's exceeded, they switch to heuristics (so the resulting diff is no longer guaranteed to be minimal). This reduces the worst-case runtime from O(N*2) to O(N*1.5).