PcoWSkbVqDnWTu_dm2ix
We use cookies on this site to enhance your user experience

Jul 03 2018, 10:27 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.

Procedure

  • 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
            end
        end
        --switch minimum with current position
        tab[i], tab[minimum] = tab[minimum], tab[i]
    end
end
Tags:
  • sort
  • algorithms
  • coding
  • reference