implementation based on the pseudocode from the CLRS