Improved and refactored sort and search code