added sort_f and made optimization