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]
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?