Stable sort

In Windows PowerShell if you do something like this:

PS> (1..20 | Sort-Object -Property {$_ % 3}) -join ‘ ‘
9 6 12 15 3 18 19 16 13 10 4 1 7 20 17 2 8 11 5 14

The results come back in an unexpected order. This is not a stable sort as the results are sorted by their modulus result but lose the order within each group.

If you want a stable sort – where the results come back from a calculation like this in the order in they were received you need to add the –Stable switch. BUT that was added to PowerShell v6.1 and later 

PS> (1..20 | Sort-Object -Property {$_ % 3} -Stable ) -join ‘ ‘
3 6 9 12 15 18 1 4 7 10 13 16 19 2 5 8 11 14 17 20

The results are sorted by modulus result and correctly within each group of modulus results

You could also use the Top or Bottom parameters:

PS> (1..20 | Sort-Object -Property {$_ % 3} -Top 20 ) -join ‘ ‘
3 6 9 12 15 18 1 4 7 10 13 16 19 2 5 8 11 14 17 20
PS> (1..20 | Sort-Object -Property {$_ % 3} -Bottom 20 ) -join ‘ ‘
3 6 9 12 15 18 1 4 7 10 13 16 19 2 5 8 11 14 17 20

If you alter the values presented to Top and Bottom you’ll get a subset of the results

PS> (1..20 | Sort-Object -Property {$_ % 3} -Top 10 ) -join ‘ ‘
3 6 9 12 15 18 1 4 7 10
PS> (1..20 | Sort-Object -Property {$_ % 3} -Bottom 10 ) -join ‘ ‘
13 16 19 2 5 8 11 14 17 20

Sort-Object in PowerShell Core has an interesting set of additions compared to Windows PowerShell.

Advertisements
This entry was posted in PowerShell v6. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s