(* This function is slow; it is O(n^2) because the @ operator is O(n) and we use it roughly n times. We will fix this in next lecture. *) fun reverse([]) = [] | reverse(first::rest) = reverse(rest) @ [first]; (* Breaks apart the given list into a tuple of two lists containing its even-indexed and odd-indexed elements respectively. If the list is of odd length, the first element of the tuple will be the longer one. Example: split([10,20,30,40,50]) = ([10,30,50], [20,40]) *) fun split([]) = ([], []) | split([value]) = ([value], []) | split(first::second::rest) = let val (a, b) = split(rest) in (first::a, second::b) end; (* Takes two SORTED lists and combines them into one big sorted list. Example: join([2,4,9,18], [1,7,8,12,20]) = [1,2,4,7,8,9,12,18,20] *) fun join([], []) = [] | join([], list2) = list2 | join(list1, []) = list1 | join(list1 as first1::rest1, list2 as first2::rest2) = if first1 < first2 then first1 :: join(rest1, list2) else first2 :: join(list1, rest2); (* Arranges the elements of the given list into sorted non-decreasing order using the recursive merge sort algorithm. *) fun mergeSort([]) = [] | mergeSort([value]) = [value] | mergeSort(L) = let val (left, right) = split(L) in join(mergeSort(left), mergeSort(right)) end; (* test data *) val jointest = ([2, 4, 9, 18], [1, 7, 8, 12, 20]); val mergesorttest = [5,2,8,4,9,6, 99, ~2, 15, 21, 0];