本文介绍了为什么我的合并排序不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我将C#merge sort函数更改为powershell,但它不再起作用了。结果中添加了大量随机数。任何人都可以说出错了吗?非常感谢!
$ 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)
{
返回$ 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])
{
返回附加$ left $ right
}
$ result = merge $ left $ right
返回$ result
}
函数追加([System.Collectio ns.ArrayList] $ a,[System.Collections.ArrayList] $ b)
{
$ s = New-Object System.Collections.ArrayList
$ s = [System.Collections.ArrayList ] $ a + [System.Collections.ArrayList]
$ b返回$ s
}
函数合并([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)
}
}
而($ a.Count -gt 0)
{
$ s.Add($ a [0])
$ a.RemoveAt(0)
}
while($ b.Count -gt 0)
{
$ s.Add($ b [0])
$ b.RemoveAt(0)
}
返回$ s
}
$ newlist = mergeSort $ list
解决方案
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
解决方案
这篇关于为什么我的合并排序不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!