Click here to Skip to main content
15,883,988 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
I changed a C# merge sort function into powershell, but it's not working anymore. There are a lot of random numbers added to the result. Could anyone tell what's wrong? Thanks so much!


$list = 1,5,9,7,2,1,3,20, 3,8,5,1,9,5,6,4,200

function mergeSort ([System.Collections.ArrayList] $m)
{
    $result = New-Object System.Collections.ArrayList
    $left = New-Object System.Collections.ArrayList
    $right = New-Object System.Collections.ArrayList

    if($m.Count -le 1)
    {
        return $m
    }

    [int]$middle = $m.Count / 2
    for($i = 0; $i -lt $middle; $i++)
    {
        $left.Add($m[$i])
    }
    for($i = $middle; $i -lt $m.Count; $i++)
    {
        $right.Add($m[$i])
    }

    $left =  mergeSort $left
    $right = mergeSort $right

    if ($left[$($left.Count - 1)] -le $right[0])
    {
        return append $left $right
    }

    $result = merge $left $right
    return $result
}

function append ([System.Collections.ArrayList] $a, [System.Collections.ArrayList] $b)
{
    $s = New-Object System.Collections.ArrayList
    $s = [System.Collections.ArrayList] $a + [System.Collections.ArrayList] $b
    return $s
}


function merge ([System.Collections.ArrayList] $a, [System.Collections.ArrayList] $b)
{
    $s = New-Object System.Collections.ArrayList
    while($a.Count -gt 0 -and $b.Count -gt 0)
    {
        if($a[0] -lt $b[0])
        {
            $s.Add($a[0])
            $a.RemoveAt(0)
        }
        else
        {
            $s.Add($b[0])
            $b.RemoveAt(0)
        }
    }

    while($a.Count -gt 0)
    {
        $s.Add($a[0])
        $a.RemoveAt(0)
    }
    while($b.Count -gt 0)
    {
        $s.Add($b[0])
        $b.RemoveAt(0)
    }

    return $s
}

$newlist = mergeSort $list
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900