Last active
February 22, 2017 02:11
-
-
Save LouiseBC/ab5ab8c3aa9434ce6217b355d0ec6e08 to your computer and use it in GitHub Desktop.
Merge Sort in Lua
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| local mergeSort = {} | |
| local function mergeHalves(array, first, last) | |
| local left = first | |
| local leftTail = math.floor((first + last) / 2) | |
| local right = leftTail + 1 | |
| local temp = {unpack(array)} | |
| -- Compare left and right halves of array, sort into temp -- | |
| for i = first, last do | |
| if (right > last or ((array[left] <= array[right]) and left <= leftTail)) then | |
| temp[i] = array[left] | |
| left = left + 1 | |
| else | |
| temp[i] = array[right] | |
| right = right + 1 | |
| end | |
| end | |
| -- Copy sorted section back to array -- | |
| for i = first, last do | |
| array[i] = temp[i] | |
| end | |
| end | |
| function mergeSort.sort(array, first, last) | |
| -- Default: sort entire array -- | |
| local first = first or 1 | |
| local last = last or #array | |
| -- Size == 1 -- | |
| if first >= last then return end | |
| -- Split & sort halves recursively -- | |
| local middle = math.floor((first + last) / 2) | |
| mergeSort.sort(array, first, middle) | |
| mergeSort.sort(array, (middle+1), last) | |
| mergeHalves(array, first, last) | |
| end | |
| return mergeSort |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment