Created
January 5, 2015 13:01
-
-
Save JaHIY/4fcedbeab2836e426c8f to your computer and use it in GitHub Desktop.
qsort 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
#!/usr/bin/env lua | |
function qsort (t, lo, hi) | |
if lo > hi then | |
return | |
end | |
local p = lo | |
for i=lo+1, hi do | |
if (t[i] < t[lo]) then | |
p = p + 1 | |
t[p], t[i] = t[i], t[p] | |
end | |
end | |
t[p], t[lo] = t[lo], t[p] | |
qsort(t, lo, p-1) | |
qsort(t, p+1, hi) | |
end | |
function three_ways_qsort(t, lo, hi) | |
if lo >= hi then | |
return | |
end | |
local lt = lo | |
local i = lo | |
local gt = hi | |
local pivot = t[lo] | |
while i <= gt do | |
if t[i] < pivot then | |
t[lt], t[i] = t[i], t[lt] | |
lt = lt + 1 | |
i = i + 1 | |
elseif t[i] > pivot then | |
t[i], t[gt] = t[gt], t[i] | |
gt = gt - 1 | |
else | |
i = i + 1 | |
end | |
end | |
three_ways_qsort(t, lo, lt-1) | |
three_ways_qsort(t, gt+1, hi) | |
end | |
--[[ | |
t={3,2,1,5,10,6} | |
qsort(t, 1, #t) | |
for i, v in ipairs(t) do | |
print(v) | |
end | |
--]] | |
t={5,3,1,3,5,7,6,2,9,7,5,2,8,4,1} | |
three_ways_qsort(t, 1, #t) | |
for i, v in ipairs(t) do | |
print(v) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment