Improve rank algorithm