dynamic sorting algorithm