Implementation
Let’s code selection sort. It’s straightforward to implement.
Basic Implementation
function selectionSort(arr) {
const n = arr.length;
for (let i = 0; i < n - 1; i++) {
let minIndex = i;
// Find minimum in unsorted portion
for (let j = i + 1; j < n; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
// Swap if minimum is not at i
if (minIndex !== i) {
[arr[i], arr[minIndex]] = [arr[minIndex], arr[i]];
}
}
return arr;
}
def selection_sort(arr):
n = len(arr)
for i in range(n - 1):
min_index = i
# Find minimum in unsorted portion
for j in range(i + 1, n):
if arr[j] < arr[min_index]:
min_index = j
# Swap if minimum is not at i
if min_index != i:
arr[i], arr[min_index] = arr[min_index], arr[i]
return arr
Try It Yourself
🟨 JavaScript Selection Sort Implementation
📟 Console Output
Run code to see output...
Code Explanation
-
Outer loop (
i): Runs n-1 times- After each iteration, one element is in place
-
Find minimum: Inner loop finds minimum
- Starts from i+1 (unsorted portion)
- Updates minIndex when smaller element found
-
Swap: Places minimum at correct position
- Only swaps if minimum is not already at i
Edge Cases
- Empty array: Returns empty array (loops don’t run)
- Single element: Already sorted, returns as-is
- Already sorted: Still runs all passes (inefficient)
- All same values: No swaps needed, but still runs
What’s Next?
Now that you can implement it, let’s analyze its performance and complexity.
Progress 57%
Page 4 of 7
← Previous
→ Next