However that algorithm has a couple of flaws in mixed left and right ordered text, and a couple of control characters have been introduced to solve the issue: https://www.w3.org/International/questions/qa-bidi-unicode-c...
Could play a bit in https://www.babelstone.co.uk/Software/BabelPad.html to see how things work.