added sorting and recursion