However it is usually attributed to David Ricardo who explained it clearly in his 1817 book The Principles of Political Economy and Taxation in an example involving England and Portugal. In Portugal it is possible to both produce wine and cloth with less work than it takes in England. However the relative costs of producing those two goods are different in the two countries. In England it is very hard to produce wine, and only moderately difficult to produce cloth. In Portugal both are easy to produce. Therefore while it is cheaper to produce cloth in Portugal than England, it is cheaper still for Portugal to produce excess wine, and trade that for English cloth. And conversely England benefits from this trade because its cost for producing cloth has not changed but it can now get wine at closer to the cost of cloth.
Stanislaw Ulam once challenged Paul Samuelson to name one theory in all of the social sciences which is both true and nontrivial. Several years later, Samuelson responded with David Ricardo's theory of Comparative advantage.
"That it is logically true need not be argued before a mathematician; that it is not trivial is attested by the thousands of important and intelligent men who have never been able to grasp the doctrine for themselves or to believe it after it was explained to them."—Paul Samuelson