Created
July 21, 2015 17:06
-
-
Save Sh4rK/ebd5b7a39be70185500e to your computer and use it in GitHub Desktop.
LuaJIT FFI array sort
This file contains 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 function sort(arr, len, elemtype, key) | |
local INSERTION_THRESHOLD = 32 | |
local function insertionSort(arr, len) | |
for i = 1, len-1 do | |
local cur = elemtype(arr[i]) | |
local curKey = key(cur) | |
local j = i | |
while j > 0 and key(arr[j-1]) > curKey do | |
arr[j] = arr[j-1] | |
j = j - 1 | |
end | |
arr[j] = cur | |
end | |
end | |
local function swap(arr, a, b) | |
local temp = elemtype(arr[a]) | |
arr[a] = arr[b] | |
arr[b] = temp | |
end | |
local function partition(arr, len) | |
local pivotKey = key(arr[0]) | |
local first = 1 | |
local last = len - 1 | |
while first < last do | |
while first < last and key(arr[last]) >= pivotKey do | |
last = last - 1 | |
end | |
while first < last and key(arr[first]) <= pivotKey do | |
first = first + 1 | |
end | |
if first < last then | |
swap(arr, first, last) | |
end | |
end | |
if key(arr[last]) >= pivotKey then | |
last = last - 1 | |
end | |
swap(arr, 0, last) | |
return last | |
end | |
local function quickSort(arr, len) | |
if len <= INSERTION_THRESHOLD then | |
return | |
end | |
local pivotIdx = partition(arr, len) | |
quickSort(arr, pivotIdx) | |
return quickSort(arr + pivotIdx + 1, len - pivotIdx - 1) | |
end | |
quickSort(arr, len) | |
insertionSort(arr, len) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment