PowerShell Script for Bubble Sort - Simple Sorting Example
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 } } } to bubble sort an array.Examples
How to Think About It
Algorithm
Code
$arr = @(5, 3, 8, 1) 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 } } } Write-Output $arr
Dry Run
Let's trace sorting [5, 3, 8, 1] through the bubble sort code
First pass comparisons
Compare 5 and 3, swap -> [3, 5, 8, 1]; compare 5 and 8, no swap; compare 8 and 1, swap -> [3, 5, 1, 8]
Second pass comparisons
Compare 3 and 5, no swap; compare 5 and 1, swap -> [3, 1, 5, 8]
Third pass comparisons
Compare 3 and 1, swap -> [1, 3, 5, 8]
| Pass | Array State |
|---|---|
| 1 | [3, 5, 1, 8] |
| 2 | [3, 1, 5, 8] |
| 3 | [1, 3, 5, 8] |
Why This Works
Step 1: Compare adjacent elements
The code uses if ($arr[$j] -gt $arr[$j + 1]) to check if the current element is bigger than the next.
Step 2: Swap if needed
If the current element is bigger, it swaps them using a temporary variable to hold one value.
Step 3: Repeat passes
The outer loop repeats the process enough times to ensure all elements bubble up to their correct position.
Alternative Approaches
$arr = @(5, 3, 8, 1) do { $swapped = $false for ($i = 0; $i -lt $arr.Length - 1; $i++) { if ($arr[$i] -gt $arr[$i + 1]) { $temp = $arr[$i] $arr[$i] = $arr[$i + 1] $arr[$i + 1] = $temp $swapped = $true } } } while ($swapped) Write-Output $arr
$arr = @(5, 3, 8, 1) $arr = $arr | Sort-Object Write-Output $arr
Complexity: O(n^2) time, O(1) space
Time Complexity
Bubble sort uses nested loops over the array, so it takes roughly n squared steps for n elements.
Space Complexity
It sorts the array in place, so it only needs a small fixed amount of extra memory.
Which Approach is Fastest?
Using a swapped flag can reduce time on nearly sorted data, but built-in sort commands are much faster overall.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Basic Bubble Sort | O(n^2) | O(1) | Learning sorting basics |
| Bubble Sort with Swapped Flag | O(n) best, O(n^2) worst | O(1) | Nearly sorted arrays |
| PowerShell Sort-Object | O(n log n) | O(n) | Real-world sorting tasks |