In mathematics, an algorithm is a sequence of well-defined instructions. The word "rhythm" can be heard in "algorithm". Rhythm is a repeated pattern of movement or sound. The joke is talking about a math teacher that was a good dancer, and "having rhythm" refers to someone who is in tune with the music when dancing. This joke is a play on the word "algorithm", where the the last two syllables sound like "rhythm" which relate to the math teacher and dancing. 
The math teacher was a good dancer - he had algorithm .