There are a few assumptions to my answer based on the example you gave:
- Each pair has no more than one match on each side (ie, [0,1 1,2 1,3] is not allowed)
There is no circular link (ie, [0,1 1,2 2,0] is not allowed)
Your algorithm currently does not guarantee that the first pair and the last pair are in the correct location
Given that circular links are allowed, there is no "correct" first and last pair.
After the last successful swap of a chain when there is no next match, a is incremented twice (after the swap and at the end of the outer loop) causing it to skip the next item.
You could add a boolean flag for each inner loop to check
Also, yourYour algorithm only appends links to a chain to the first encountered pair in the chain, but it does not ensure a is the first item in the chain.
The result is that an example like { 1,2, 0,1, 2,3} will sort to {1,2, 2,3, 0,1} instead of {0,1, 1,2, 2,3}, so links might be split up. You could check whether the pair at b comes before the pair at a, but with circular links being legal, you need to check for the case where the whole list is one long circular chain, which could result in infinite loops.