refactor sort algrithm