From 88840a470fac0875849793583fa389290b4e56c1 Mon Sep 17 00:00:00 2001 From: zhangjiong Date: Tue, 8 Aug 2017 13:49:29 +0800 Subject: [PATCH] Add Lua code for chapter 2 --- 02_selection_sort/lua/01_selection_sort.lua | 31 +++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 02_selection_sort/lua/01_selection_sort.lua diff --git a/02_selection_sort/lua/01_selection_sort.lua b/02_selection_sort/lua/01_selection_sort.lua new file mode 100644 index 0000000..f8ea2c1 --- /dev/null +++ b/02_selection_sort/lua/01_selection_sort.lua @@ -0,0 +1,31 @@ +-- Finds the smallest value in an array +function find_smallest(array) + -- Stores the smallest value + local smallest = array[1] + -- Stores the index of the smallest value + local smallest_index = 1 + + for i = 2, #array do + if (array[i] < smallest) then + smallest = array[i] + smallest_index = i + end + end + + return smallest_index +end + +-- Sort array +function selection_sort(array) + local new_array = {} + + for i = 1, #array do + -- Finds the smallest element in the array and adds it to the new array + local smallest_index = find_smallest(array) + new_array[i] = table.remove(array, smallest_index) + end + + return new_array +end + +print(table.concat(selection_sort({5, 3, 6, 2, 10}), ", ")) \ No newline at end of file