I have implemented a simple merge sort function in PowerShell like so
function Merge-Sort
{
param($a)
if ($a.Length -gt 1)
{
$m = [Math]::floor($a.Length / 2)
[Int[]]$l = $a[0..($m-1)]
[Int[]]$r = $a[$m..($a.Length)]
Merge-Sort $l
Merge-Sort $r
$i = $j = $k = 0
while ($i -lt $l.Length -and $j -lt $r.Length)
{
if ($l[$i] -lt $r[$j])
{
$a[$k] = $l[$i]
$i++
}
else
{
$a[$k] = $r[$j]
$j++
}
$k++
}
while($i -lt $l.length)
{
$a[$k] = $l[$i]
$i++
$k++
}
while($j -lt $r.length)
{
$a[$k] = $r[$j]
$j++
$k++
}
}
}
The functions does what it should and sorts an array of integer values:
$arr = @(22,44,55,11,66,11,77,99,33,88)
merge-sort $arr
The output is: 11 11 22 33 44 55 66 77 88 99
But when I define the function parameter as [Int[]] to make clear that it should be an array of integers instead of object something went wrong and the array stays unsorted:
function Merge-Sort
{
param([Int[]]$a)
...
}
The output is: 22 44 55 11 66 11 77 99 33 88
My question is:
Why does the correct way to define the function parameter leads to an incorrect result (the array does not get sorted)?
[array]::Sort()method that will do an in-place sort of an array. there is also a[array]::Reverse()in there for giggles. [grin]