Proper solution based on merge sort algorithm.