Fixes a bug in sort_by_key algorithm

Values were written over by junk data instead of being sorted by keys.
Moreover, this was not covered by tests.

Closes #104, closes #105.