Selection Sorting
Selection sort divides a list into sorted and unsorted parts, repeatedly finding the minimum (or maximum) element from the unsorted portion and swapping it into place. It runs in O(n²) time across best, average, and worst cases with O(1) space.
Theory & Explanation
Selection Sort: Definition, Stepwise Working, Complexity & Code
1. Definition & Key Characteristics
Selection Sort is an in-place comparison sorting algorithm that divides a list into two parts: a sorted subarray on the left (initially empty) and an unsorted subarray on the right (initially the entire list). In each pass, it finds the smallest (minimum) element in the unsorted subarray (for ascending order) and swaps it with the leftmost element of the unsorted subarray, expanding the sorted boundary by one position.
- In-Place Sorting: Uses only a few index/temporary variables, requiring
O(1)auxiliary space. - Minimizes Swaps: Performs at most
n - 1swaps in total (one per pass), unlike bubble sort which may swap on every adjacent comparison. - Not Stable (in Standard Swap): Swapping a minimum element with an earlier element can change the relative order of equal keys (for example, swapping
20awith a later10past20b). - Input-Insensitive Comparisons: Always performs
n(n - 1)/2comparisons regardless of whether the array is already sorted, reverse-sorted, or random.
2. How Selection Sort Works (Step-by-Step Algorithm)
- Let the array have
nelements at indices0ton - 1. - Run an outer loop
ifrom0ton - 2(representing the boundary index where the next smallest element should be placed). - Assume the minimum element is at index
i: setminIdx = i. - Scan the unsorted portion using an inner loop
jfromi + 1ton - 1:- If
arr[j] < arr[minIdx], updateminIdx = j.
- If
- After the inner loop finishes, if
minIdx != i, swaparr[i]andarr[minIdx]. - Repeat until
ireachesn - 2; the array is then completely sorted.
3. Step-by-Step Example & Graphical Representation
Sort arr = [40, 20, 30, 10] (n = 4) in ascending order:
- Pass 1 (
i = 0, search unsorted range0..3):- Start with
minIdx = 0(value40). - Compare with
20(idx 1) →minIdx = 1; compare with30(idx 2) → keep1; compare with10(idx 3) →minIdx = 3(value10). - Swap
arr[0](40) andarr[3](10) →[10, 20, 30, 40]. Sorted prefix:[10].
- Start with
- Pass 2 (
i = 1, search unsorted range1..3):- Minimum in
[20, 30, 40]is20atminIdx = 1. minIdx == i, so no swap needed →[10, 20, 30, 40]. Sorted prefix:[10, 20].
- Minimum in
- Pass 3 (
i = 2, search unsorted range2..3):- Minimum in
[30, 40]is30atminIdx = 2. minIdx == i, so no swap needed →[10, 20, 30, 40]. Sorted prefix:[10, 20, 30](and40is automatically in place).
- Minimum in
Graphical Representation: Stepwise Passes of Selection Sort on [40, 20, 30, 10]
4. Time & Space Complexity Analysis
| Case | Condition | Comparisons | Swaps | Time Complexity |
|---|---|---|---|---|
| Best Case | Array is already sorted | n(n - 1)/2 |
0 |
O(n2) |
| Average Case | Randomly ordered elements | n(n - 1)/2 |
At most n - 1 |
O(n2) |
| Worst Case | Array is sorted in reverse order | n(n - 1)/2 |
At most n - 1 |
O(n2) |
Auxiliary Space Complexity: O(1) (in-place sorting).
5. C Program: Selection Sort
#include <stdio.h>
void selectionSort(int arr[], int n) {
for (int i = 0; i < n - 1; i++) {
int minIdx = i; // Assume current position holds the minimum
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[minIdx]) {
minIdx = j; // Found a smaller element
}
}
if (minIdx != i) {
int temp = arr[i];
arr[i] = arr[minIdx];
arr[minIdx] = temp;
}
}
}
void printArray(int arr[], int n) {
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
int main() {
int arr[] = {40, 20, 30, 10};
int n = sizeof(arr) / sizeof(arr[0]);
printf("Original array: ");
printArray(arr, n);
selectionSort(arr, n);
printf("Sorted array (Ascending): ");
printArray(arr, n);
return 0;
}
Expected Output (C):
Original array: 40 20 30 10
Sorted array (Ascending): 10 20 30 40
6. Python Program: Selection Sort
def selection_sort(arr):
n = len(arr)
for i in range(n - 1):
min_idx = i
for j in range(i + 1, n):
if arr[j] < arr[min_idx]:
min_idx = j
if min_idx != i:
arr[i], arr[min_idx] = arr[min_idx], arr[i]
return arr
if __name__ == "__main__":
data = [40, 20, 30, 10]
print("Original array:", data)
sorted_data = selection_sort(data[:])
print("Sorted array (Ascending):", sorted_data)
Expected Output (Python):
Original array: [40, 20, 30, 10]
Sorted array (Ascending): [10, 20, 30, 40]