Lua Merge Sort Implementation
function mergeSort(arr) if arr == nil or #arr <= 1 then return arr -- Already sorted or empty end local mid = math.floor(#arr / 2) local left = table.move(arr, 1, mid, 1, {}) local right = table.move(arr, mid + 1, #arr, 1, {}) left = mergeSort(left) right = mergeSort(right) retur...
This Lua code implements the Merge Sort algorithm, a highly efficient, comparison-based sorting technique. It recursively divides the input array into halves, sorts them, and then merges the sorted halves. Merge Sort is...
The `mergeSort` function recursively sorts an array. The base case is when the array has 0 or 1 element, in which case it's already sorted. Otherwise, it splits the array into two halves (`left` and `right`), recursively sorts each half, and then merges the two sorted halves using the `merge` function. The `merge` function takes two sorted arrays and combines them into a single sorted array. It uses two pointers, `i` and `j`, to iterate through `left` and `right` respectively. It compares elements from both arrays and inserts the smaller element into the `result` array, advancing the corresponding pointer. After one of the arrays is exhausted, any remaining elements from the other array are appended. The time complexity of Merge Sort is O(n log n) due to the recursive division and linear merging steps. The space complexity is O(n) because of the auxiliary space required for the `result` array during merging and for storing the subarrays in recursive calls.
function mergeSort(array): if length(array) <= 1: return array calculate mid_point = floor(length(array) / 2) create left_half from array[1 to mid_point] create right_half from array[mid_point + 1 to end] sorted_left = m...