Selection Sort
Selection Sort repeatedly picks the minimum (or maximum) from the unsorted part and places it at the end of the sorted part until done.
Click "Step forward" to watch the algorithm state change.
- In each pass, find the minimum in the unsorted part and swap with its first element.
- Repeat passes until fully sorted.
Pseudo-code:
for i = 0 to n-2:
min = i
for j = i+1 to n-1:
if A[j] < A[min]:
min = j
if min != i:
swap(A[i], A[min])
void SelectSort(int A[], int n) {
for (int i = 0; i < n - 1; i++) {
int min = i; // the index of the smallest element
for (int j = i + 1; j < n; j++) {
if (A[j] < A[min]) min = j; // found a smaller element
}
if (min != i) { // swap it into the end of the sorted part
int tmp = A[i];
A[i] = A[min];
A[min] = tmp;
}
}
}
The Connection to Heap Sort
Simple selection sort has to scan the remaining part on every pass, so the number of comparisons is always . Heap sort uses the heap structure to bring the cost of “finding the smallest element” down from to , which lowers the overall complexity from to .
- Best/worst/avg:
- Space:
- Stability: unstable
Exercise 1
Run selection sort on and show each pass.
Approach: Each pass selects the smallest remaining element and moves it to the front.
Steps:
- Initial: [64, 25, 12, 22, 11]
- Pass 1: [11, 25, 12, 22, 64]
- Pass 2: [11, 12, 25, 22, 64]
- Pass 3: [11, 12, 22, 25, 64]
- Pass 4: [11, 12, 22, 25, 64]
Answer: As shown above; after every pass the minimum of the remaining suffix sits in its final position.
Exercise 2
What are the time and space complexities of selection sort?
Approach: Consider the time complexity and the extra space.
Steps:
- Time complexity
- Space complexity
Answer: Time , space .
