We use cookies on this site to enhance your user experience

Aug 29 2019, 9:23 AM PST 5 min

Selection Sort is a data sorting algorithm. The selection sort is one of the least efficient, but simple, sorting algorithms. It has a complexity of O(n2) which makes it very impractical for large sets of data.


  • Search for the minimum number in the remaining section of the list.
  • Swap with the current position.
  • Repeat until the end of the list is reached.

Example Code

--Sort the table tab in place
function selection_sort(tab)
    --Go through every position in the table
    for i = 1, #tab do
        --start minimum at current position
        local minimum = i
        --Go through the remaining elements that need to be sorted
        for t = i + 1, #tab do
            --compare current element to minimum
            if tab[t] < tab[minimum] then
                --t is the new minimum
                minimum = t
        --switch minimum with current position
        tab[i], tab[minimum] = tab[minimum], tab[i]
  • sort
  • algorithms
  • coding
  • reference