adds sort_by function template and uses it in Palette and Quantize