How do I implement merge sort in Swift?

Merge sort is a classic divide-and-conquer algorithm that sorts an array by recursively splitting it into smaller subarrays, sorting those, and then merging them back together. Here’s how to implement merge sort in Swift.

func mergeSort(_ array: [Int]) -> [Int] { // Base case guard array.count > 1 else { return array } // Split the array into halves let middleIndex = array.count / 2 let leftArray = mergeSort(Array(array[0.. [Int] { var leftIndex = 0 var rightIndex = 0 var mergedArray: [Int] = [] // Compare elements from the left and right arrays and merge them while leftIndex < left.count && rightIndex < right.count { if left[leftIndex] < right[rightIndex] { mergedArray.append(left[leftIndex]) leftIndex += 1 } else { mergedArray.append(right[rightIndex]) rightIndex += 1 } } // Append remaining elements from the left array if any while leftIndex < left.count { mergedArray.append(left[leftIndex]) leftIndex += 1 } // Append remaining elements from the right array if any while rightIndex < right.count { mergedArray.append(right[rightIndex]) rightIndex += 1 } return mergedArray } // Example usage let unsortedArray = [38, 27, 43, 3, 9, 82, 10] let sortedArray = mergeSort(unsortedArray) print(sortedArray) // Output: [3, 9, 10, 27, 38, 43, 82]

merge sort swift sorting algorithm divide and conquer sorting in swift