How do I implement the merge two sorted lists in Swift?

In Swift, you can merge two sorted lists into a single sorted list using a two-pointer technique. This involves iterating through both lists and comparing the current elements, adding the smaller one to the result list until one of the lists is exhausted. Finally, append any remaining elements from the other list. Below is an example of how to implement this functionality:

func mergeSortedLists(_ list1: [T], _ list2: [T]) -> [T] { var mergedList = [T]() var i = 0 var j = 0 while i < list1.count && j < list2.count { if list1[i] < list2[j] { mergedList.append(list1[i]) i += 1 } else { mergedList.append(list2[j]) j += 1 } } // Append remaining elements while i < list1.count { mergedList.append(list1[i]) i += 1 } while j < list2.count { mergedList.append(list2[j]) j += 1 } return mergedList } // Example usage let list1 = [1, 3, 5, 7] let list2 = [2, 4, 6, 8] let merged = mergeSortedLists(list1, list2) print(merged) // Output: [1, 2, 3, 4, 5, 6, 7, 8]

merge sorted lists swift two-pointer technique algorithm