Selection Sort Algorithm in DSA Python - Time & Space Complexity
We want to understand how the time taken by Selection Sort changes as the list gets bigger.
How does the number of steps grow when sorting more items?
Analyze the time complexity of the following code snippet.
def selection_sort(arr):
n = len(arr)
for i in range(n):
min_index = i
for j in range(i + 1, n):
if arr[j] < arr[min_index]:
min_index = j
arr[i], arr[min_index] = arr[min_index], arr[i]
This code sorts a list by repeatedly finding the smallest item and moving it to the front.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Comparing elements inside the inner loop to find the smallest value.
- How many times: The inner loop runs fewer times each pass but overall about n x (n - 1) / 2 times.
As the list size grows, the number of comparisons grows roughly with the square of the size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 45 comparisons |
| 100 | About 4,950 comparisons |
| 1000 | About 499,500 comparisons |
Pattern observation: Doubling the input size roughly quadruples the work needed.
Time Complexity: O(n²)
This means the time to sort grows roughly with the square of the number of items.
[X] Wrong: "Selection Sort gets faster if the list is already sorted."
[OK] Correct: Selection Sort always checks all elements to find the minimum, so it takes the same time regardless of order.
Understanding Selection Sort's time helps you compare it with faster methods and shows you how to analyze nested loops clearly.
"What if we stopped searching for the minimum after finding the first smaller element? How would the time complexity change?"
Practice
Selection Sort algorithm?Solution
Step 1: Understand Selection Sort process
Selection Sort works by finding the smallest element in the unsorted part and swapping it with the first unsorted element.Step 2: Compare with other sorting methods
Other options describe different algorithms: merge sort, bubble sort, and quicksort, not selection sort.Final Answer:
Repeatedly find the smallest element and move it to the front -> Option AQuick Check:
Selection Sort = Find smallest and swap [OK]
- Confusing selection sort with bubble sort
- Thinking it divides the list like merge sort
- Mixing it up with quicksort's pivot method
a[i] and a[j] in Python during selection sort?Solution
Step 1: Identify Pythonic swap syntax
Python allows swapping two variables in one line:a[i], a[j] = a[j], a[i].Step 2: Check other options for correctness
temp = a[i]; a[i] = a[j]; a[j] = a[i] causes data loss by overwriting without properly using temp; swap(a[i], a[j]) is invalid syntax; a[i] = a[j]; a[j] = a[i] causes both to have same value.Final Answer:
a[i], a[j] = a[j], a[i] -> Option BQuick Check:
Python swap = a[i], a[j] = a[j], a[i] [OK]
- Using a function swap() which doesn't exist
- Assigning one element twice causing data loss
- Not using tuple unpacking for swap
def selection_sort(arr):
for i in range(len(arr)):
min_idx = i
for j in range(i+1, len(arr)):
if arr[j] < arr[min_idx]:
min_idx = j
arr[i], arr[min_idx] = arr[min_idx], arr[i]
arr = [3, 1, 4]
selection_sort(arr)
print(arr)Solution
Step 1: Trace first iteration of outer loop
i=0, min_idx=0; inner loop finds smallest element from index 1 and 2. arr[1]=1 < arr[0]=3, so min_idx=1. Swap arr[0] and arr[1]: arr becomes [1, 3, 4].Step 2: Trace second iteration
i=1, min_idx=1; inner loop checks arr[2]=4 which is not less than arr[1]=3, so no swap. Array stays [1, 3, 4].Final Answer:
[1, 3, 4] -> Option DQuick Check:
Sorted array = [1, 3, 4] [OK]
- Not swapping when min_idx changes
- Confusing indices in inner loop
- Assuming array is unchanged
def selection_sort(arr):
for i in range(len(arr)):
min_idx = i
for j in range(i+1, len(arr)):
if arr[j] > arr[min_idx]:
min_idx = j
arr[i], arr[min_idx] = arr[min_idx], arr[i]Solution
Step 1: Analyze the if condition logic
The code uses 'if arr[j] > arr[min_idx]' which finds the largest element, but selection sort needs the smallest.Step 2: Correct the comparison operator
Changing '>' to '<' will correctly find the smallest element to swap.Final Answer:
Change '>' to '<' in the if condition to find the smallest element -> Option CQuick Check:
Selection sort finds minimum, so use '<' [OK]
- Using '>' causes sorting in descending order
- Swapping outside loop breaks logic
- Wrong initialization of min_idx
arr = [5, 3, 8, 3, 9], how many swaps will the selection sort algorithm perform to sort this list in ascending order?Solution
Step 1: Trace selection sort swaps step-by-step
Initial array: [5, 3, 8, 3, 9] - i=0: smallest is 3 at index 1, swap arr[0] and arr[1] -> [3, 5, 8, 3, 9] (1 swap) - i=1: smallest is 3 at index 3, swap arr[1] and arr[3] -> [3, 3, 8, 5, 9] (2 swaps) - i=2: smallest is 5 at index 3, swap arr[2] and arr[3] -> [3, 3, 5, 8, 9] (3 swaps) - i=3: smallest is 8 at index 3, no swap needed - i=4: last element, no swap neededStep 2: Count total swaps
Total swaps performed = 3.Final Answer:
3 -> Option AQuick Check:
Swaps counted = 3 [OK]
- Counting swaps even when min_idx equals i
- Assuming one swap per iteration always
- Ignoring repeated elements affecting swaps
Ready to prove it?
Pass the test and this pattern moves unknown
