// Find the index of the smallest element in the unsorted portion
'''for''' j ← i + 1 '''to''' len - 1 '''do'''
'''if''' arr[j] < arr[minIndex] '''THEN'''
minIndex ← j
// Swap if a new minimum was found
'''if''' minIndex != i '''THEN'''
'''swap''' arr[i] '''with''' arr[minIndex]
'''return''' arr
Below is an implementation in [[C (programming language)|C]].
<syntaxhighlight lang="c" style="overflow:auto; width:auto;" line="1"> /* a[0] to a[aLength-1] is the array to sort */
int i,j;
int aLength; // initialise to a's length
Line 122 ⟶ 106:
swap(&a[i], &a[jMin]);
}
}
}</syntaxhighlight>
== Complexity ==
Analyzing selectionSelection sort is simplifiednot difficult to analyze compared to other sorting algorithms, since none of the loops depend on the data in the array. Selecting the minimum requires scanning <math>n</math> elements (taking <math>n-1</math> comparisons) and then swapping it into the first position. Finding the next lowest element requires scanning the remaining <math>n-1</math> elements (taking <math>n-2</math> comparisons) and so on. Therefore, the total number of comparisons is given as