PlanetMath (more info)
 Math for the people, by the people.
Encyclopedia | Requests | Forums | Docs | Wiki | Random | RSS  
Login
create new user
name:
pass:
forget your password?
Main Menu
selection sort (Algorithm)

The Problem

See the Sorting Problem.

The Algorithm

Suppose $ L = \left\{ x_1, x_2, \dots, x_n\right\}$ is the initial list of unsorted elements. The selection sort algorithm sorts this list in $ n$ steps. At each step $ i$, find the largest element $ L[j]$ such that $ j < n - i + 1$, and swap it with the element at $ L[n - i + 1]$. So, for the first step, find the largest value in the list and swap it with the last element in the list. For the second step, find the largest value in the list up to (but not including) the last element, and swap it with the next to last element. This is continued for $ n - 1$ steps. Thus the selection sort algorithm is a very simple, in-place sorting algorithm.

Pseudocode

Algorithm SELECTION_SORT(L, n)
Input: A list $ L$ of $ n$ elements
Output: The list $ L$ in sorted order

begin
$\textstyle \parbox{\textwidth}{ \textbf{for} $i \gets n\mbox{ downto }2$\ \text... ...\gets j$}} \ $L[i] \gets L[max]$\ \ $L[max] \gets temp$ }\\ \textbf{end} }}$
end

Analysis

The selection sort algorithm has the same runtime for any set of $ n$ elements, no matter what the values or order of those elements are. Finding the maximum element of a list of $ i$ elements requires $ i - 1$ comparisons. Thus $ T(n)$, the number of comparisons required to sort a list of $ n$ elements with the selection sort, can be found:


$\displaystyle T(n)$ $\displaystyle =$ $\displaystyle \sum_{i=2}^n(i-1)$  
  $\displaystyle =$ $\displaystyle \sum_{i=1}^ni-n-2$  
  $\displaystyle =$ $\displaystyle \frac{(n^2-n-4)}{2}$  
  $\displaystyle =$ $\displaystyle \mathcal{O}(n^2)$  

However, the number of data movements is the number of swaps required, which is $ n-1$. This algorithm is very similar to the insertion sort algorithm. It requires fewer data movements, but requires more comparisons.



"selection sort" is owned by mathcam. [ full author list (2) | owner history (2) ]
(view preamble)

View style:

See Also: insertion sort, sorting problem


Cross-references: insertion sort, order
There is 1 reference to this entry.

This is version 2 of selection sort, born on 2001-10-08, modified 2004-04-27.
Object id is 182, canonical name is SelectionSort.
Accessed 7003 times total.

Classification:
AMS MSC68P10 (Computer science :: Theory of data :: Searching and sorting)

Pending Errata and Addenda
None.
[ View all 2 ]
Discussion
Style: Expand: Order:
forum policy
Linking Bug? by mathcam on 2004-07-13 15:46:45
I'm having a hard time fixing this correction. Every time I try to force the link, it replace "The Sorting Problem" with "@@@@@" or something to that effect. Anyone seen this before?

Cam
[ reply | up ]

Interact
rate | post | correct | update request | add example | add (any)