Selection sort: Difference between revisions

Content deleted Content added
Ajmullen (talk | contribs)
Added pseudocode implementation of sort
Tags: Reverted Visual edit
Restored revision 1283058976 by 0x1F80104E (talk): Redundant
 
Line 77:
 
== Implementations ==
Below is [[Pseudocode]] that implements selection sort based off of the example given above.
'''function''' selectionSort('''array''' arr) '''is'''
len ← '''length'''(arr)
// Loop through each position in the array
'''for''' i ← 0 '''to''' len - 2 '''do'''
minIndex ← i
// 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
 
: <math>(n-1)+(n-2)+\dots+1 =