Skip to content

Commit 5f2626c

Browse files
zhangjiongwxegonSchiele
authored andcommitted
Add Lua code for chapter 4
1 parent e301696 commit 5f2626c

File tree

5 files changed

+73
-0
lines changed

5 files changed

+73
-0
lines changed

04_quicksort/lua/01_loop_sum.lua

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
function sum(array)
2+
local total = 0
3+
4+
for _, value in pairs(array) do
5+
total = total + value
6+
end
7+
8+
return total
9+
end
10+
11+
print(sum({1, 2, 3, 4})) -- => 10

04_quicksort/lua/02_recursive_sum.lua

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
function sum(array)
2+
if next(array) == nil then
3+
return 0;
4+
end
5+
6+
return array[1] + sum(table.move(array, 2, #array, 1, {}))
7+
end
8+
9+
print(sum({1, 2, 3, 4})) -- => 10
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
function count(array)
2+
if next(array) == nil then
3+
return 0
4+
end
5+
6+
return 1 + count(table.move(array, 2, #array, 1, {}))
7+
end
8+
9+
print(count({1, 2, 3, 4})) -- => 4

04_quicksort/lua/04_recursive_max.lua

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
function max(array)
2+
if next(array) == nil then
3+
return nil
4+
elseif #array == 1 then
5+
return array[1]
6+
elseif #array == 2 then
7+
return array[1] > array[2] and array[1] or array[2]
8+
end
9+
10+
local sub_max = max(table.move(array, 2, #array, 1, {}))
11+
return array[1] > sub_max and array[1] or sub_max
12+
end
13+
14+
print(max({1, 2, 3, 4})) -- => 4

04_quicksort/lua/05_quicksort.lua

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
function concat(array1, array2)
2+
for _, value in pairs(array2) do
3+
table.insert(array1, value)
4+
end
5+
6+
return array1
7+
end
8+
9+
function quicksort(array)
10+
if #array < 2 then
11+
-- base case, arrays with 0 or 1 element are already "sorted"
12+
return array
13+
else
14+
-- recursive case
15+
local pivot = array[1]
16+
local less, greater = {}, {}
17+
18+
for i = 2, #array do
19+
if array[i] <= pivot then
20+
table.insert(less, array[i])
21+
else
22+
table.insert(greater, array[i])
23+
end
24+
end
25+
26+
return concat(quicksort(less), concat({pivot}, quicksort(greater)))
27+
end
28+
end
29+
30+
print(table.concat(quicksort({10, 5, 2, 3}), ", "))

0 commit comments

Comments
 (0)