PowerShell Script for Selection Sort Algorithm
for ($i=0; $i -lt $arr.Length-1; $i++) { $minIndex = $i; for ($j=$i+1; $j -lt $arr.Length; $j++) { if ($arr[$j] -lt $arr[$minIndex]) { $minIndex = $j } } if ($minIndex -ne $i) { $temp = $arr[$i]; $arr[$i] = $arr[$minIndex]; $arr[$minIndex] = $temp } }.Examples
How to Think About It
Algorithm
Code
function SelectionSort([int[]]$arr) { for ($i = 0; $i -lt $arr.Length - 1; $i++) { $minIndex = $i for ($j = $i + 1; $j -lt $arr.Length; $j++) { if ($arr[$j] -lt $arr[$minIndex]) { $minIndex = $j } } if ($minIndex -ne $i) { $temp = $arr[$i] $arr[$i] = $arr[$minIndex] $arr[$minIndex] = $temp } } return $arr } # Example usage $arr = 5,3,8,1 $sorted = SelectionSort $arr Write-Output $sorted
Dry Run
Let's trace sorting the array [5, 3, 8, 1] through the code
First pass
Start at index 0 (value 5). Find smallest from index 0 to end: smallest is 1 at index 3. Swap 5 and 1. Array becomes [1, 3, 8, 5].
Second pass
At index 1 (value 3). Find smallest from index 1 to end: smallest is 3 at index 1. No swap needed. Array stays [1, 3, 8, 5].
Third pass
At index 2 (value 8). Find smallest from index 2 to end: smallest is 5 at index 3. Swap 8 and 5. Array becomes [1, 3, 5, 8].
| Iteration | Array State |
|---|---|
| 1 | [1, 3, 8, 5] |
| 2 | [1, 3, 8, 5] |
| 3 | [1, 3, 5, 8] |
Why This Works
Step 1: Finding the smallest element
The inner loop uses -lt to compare elements and find the smallest value in the unsorted part.
Step 2: Swapping elements
If a smaller element is found, it swaps places with the current element using a temporary variable.
Step 3: Repeating for all elements
The outer loop moves the boundary of the sorted part forward until the whole array is sorted.
Alternative Approaches
$arr = 5,3,8,1 $sorted = $arr | Sort-Object Write-Output $sorted
function BubbleSort([int[]]$arr) { for ($i = 0; $i -lt $arr.Length - 1; $i++) { for ($j = 0; $j -lt $arr.Length - $i - 1; $j++) { if ($arr[$j] -gt $arr[$j + 1]) { $temp = $arr[$j] $arr[$j] = $arr[$j + 1] $arr[$j + 1] = $temp } } } return $arr } $arr = 5,3,8,1 $sorted = BubbleSort $arr Write-Output $sorted
Complexity: O(n^2) time, O(1) space
Time Complexity
Selection sort uses two nested loops over the array, resulting in O(n^2) time because it compares each element with all others.
Space Complexity
It sorts the array in place using only a few extra variables, so space complexity is O(1).
Which Approach is Fastest?
Using PowerShell's built-in Sort-Object is fastest and simplest, but selection sort teaches the sorting logic clearly.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Selection Sort | O(n^2) | O(1) | Learning sorting basics |
| Bubble Sort | O(n^2) | O(1) | Simple concept, less efficient |
| Sort-Object cmdlet | O(n log n) | O(n) | Real-world sorting tasks |