Lua - Selection Sort



Selection Sort selects the minimum element from a unsorted part of the list repeatedly and then swaps the same with the first element of the unsorted list.

main.lua

-- function to sort a list using selection sort
function selection_sort(list)
   -- length of the list
   local n = #list 
   -- start iterating from 1st element till second last element
   for i = 1, n-1 do 
      -- initialize index of minimum element
      local minIndex = i 
      -- Find the index of the minimum element in the unsorted part of the list
      for j = i + 1, n do
         if list[j] < list[minIndex] then
            minIndex = j -- minIndex should point to minimum element
         end
      end

      -- swap the minIndex with the first element
      if minIndex ~= i then
         list[i], list[minIndex] = list[minIndex], list[i]
      end
   end
   -- list is sorted, return it
   return list 
end

-- Example usage:
local numbers = {5, 1, 4, 2, 8}
local sorted = selection_sort(numbers)
print("Sorted list:", table.concat(sorted, ", "))

Output

When we run the above program, we will get the following output−

Sorted list:	1, 2, 4, 5, 8

Working of Selection Sort

  • Iterate through each element − We've started loop from 1st element to second last element. Target is to put correct element at the ith position with each iteration.

  • Find the minimumminIndex is used to get the index of minimum element. An inner loop is used to iterate the unsorted part of the list and get the index of minimum element.

  • Swapping − Once inner loop completes, we're checking if minIndex is different from i then values are swapped to put the minimum element of the unsorted list in its correct position in the list.

  • Repeat the process − The outer loop continues and after each iteration, the minimum element from each iteration is placed in their correct positions.

  • Building the Sorted List − The above steps are repeated until the list is sorted.

Time Complexity

  • O(n2) −, where n is number of elements as we always loop inner loops. Outer loops runs n-1 times and on average inner loop run n/2. So worst-case, best-case and average time complexities are of O(n2).

Space Complexity

  • O(1) − Space complexity of selection sort is constant as it is not requiring any extra memory from the list for any temporary storage.

When to use Selection Sort

Selection sort is simple and easy to learn and is used in following areas −

  • Educational Purpose − Being simple and easy to learn/teach, seletion sort is preferred for educational purposes.

  • Small Set of Data − In case of smaller set of data, selection sort performance is at par with other algorithms.

  • Less Swaps − In case, swapping operations are costly, Selection sort is useful, as it performs minimal number of swaps, O(n).

Advertisements