- 2074 Bhadra · 10 marks
Selection sort with trace
Short answer
Selection sort finds the smallest element in the unsorted part and swaps it to the front. Sorting 40, 90, 20, -10, 30, 5, 60, 100, 80: after each pass, the array becomes -10, 5, 20, 30, 40, 60, 80, 90, 100. The final sorted sequence is -10, 5, 20, 30, 40, 60, 80, 90, 100.
Explain selection sort. Sort data sequence 40 90 20 -10 30 5 60 100 80 using selection sort method.
Selection sort repeatedly selects the smallest element from the unsorted part and exchanges it with the first element of that part. After pass i, the first i positions hold the i smallest elements in their final places.
Algorithm
SelectionSort(a[0..n-1])
for i = 0 to n-2
min = i
for j = i+1 to n-1
if a[j] < a[min]: min = j
swap a[i], a[min]
void selection_sort(int a[], int n) {
int i, j, min, t;
for (i = 0; i < n - 1; i++) {
min = i; /* index of smallest so far */
for (j = i + 1; j < n; j++)
if (a[j] < a[min]) min = j;
t = a[i]; a[i] = a[min]; a[min] = t; /* exchange */
}
}
Trace for 40 90 20 −10 30 5 60 100 80 (n = 9, 8 passes)
| Pass | Smallest found | Swap | Array after pass |
|---|---|---|---|
| 0 | – | – | 40 90 20 −10 30 5 60 100 80 |
| 1 | −10 | a[0] ↔ a[3] | −10 90 20 40 30 5 60 100 80 |
| 2 | 5 | a[1] ↔ a[5] | −10 5 20 40 30 90 60 100 80 |
| 3 | 20 | already in place | −10 5 20 40 30 90 60 100 80 |
| 4 | 30 | a[3] ↔ a[4] | −10 5 20 30 40 90 60 100 80 |
| 5 | 40 | already in place | −10 5 20 30 40 90 60 100 80 |
| 6 | 60 | a[5] ↔ a[6] | −10 5 20 30 40 60 90 100 80 |
| 7 | 80 | a[6] ↔ a[8] | −10 5 20 30 40 60 80 100 90 |
| 8 | 90 | a[7] ↔ a[8] | −10 5 20 30 40 60 80 90 100 |
Sorted: −10, 5, 20, 30, 40, 60, 80, 90, 100
Complexity
- Comparisons: (n−1) + (n−2) + ... + 1 = n(n−1)/2 in every case, so time is O(n²) (best, average and worst).
- At most n − 1 swaps, which is good when writes are costly.
- In-place (O(1) space) and not stable.
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- Straight selection sort on 33, 90, 45, ... · Data Structure and Algorithm, chapter 7
- AVL tree for 10 20 30 50 45 40 8 5 3 · Data Structure and Algorithm, chapter 6
- AVL tree for 10, 20, 30, 35, 50, ... · Data Structure and Algorithm, chapter 6
- Merge sort algorithm and trace · Data Structure and Algorithm, chapter 7
- Efficiency of straight selection sort · Data Structure and Algorithm, chapter 7
- Radix sort on 32, 45, 60, 83, ... · Data Structure and Algorithm, chapter 7
- Conductor selection, 100 MW 70 km 132 kV · Transmission and Distribution System Design, chapter 4
- Arch 100 m: rolling UDL 60 m, section at 30 m · Theory of Structures I, chapter 6
- Conductor selection, 100 MW 80 km, no corona · Transmission and Distribution System Design, chapter 4
- Microwave link: 90 km, 10 GHz, 40 dB antennas · Propagation and Antenna, chapter 5