gpt4 book ai didi

java - 这部分代码会在归并排序中执行吗?

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:18:55 24 4
gpt4 key购买 nike

归并排序的算法是

Step 1 − if it is only one element in the list it is already sorted, return. Step 2 − divide the list recursively into two halves until it can no more be divided. Step 3 − merge the smaller lists into new list in sorted order.

用这个伪代码:

procedure mergesort( var a as array )
if ( n == 1 ) return a

var l1 as array = a[0] ... a[n/2]
var l2 as array = a[n/2+1] ... a[n]

l1 = mergesort( l1 )
l2 = mergesort( l2 )

return merge( l1, l2 )
end procedure

procedure merge( var a as array, var b as array )

var c as array

while ( a and b have elements )
if ( a[0] > b[0] )
add b[0] to the end of c
remove b[0] from b
else
add a[0] to the end of c
remove a[0] from a
end if
end while

while ( a has elements )
add a[0] to the end of c
remove a[0] from a
end while

while ( b has elements )
add b[0] to the end of c
remove b[0] from b
end while

return c

end procedure

我的问题是:

merge 函数中,有两个while 循环来检查ab 是否还有项目并将它们添加到c 数组。

我的问题是这两个 while 会(可以)在同一个函数中执行吗?

或者如果 a 仍然有项目,这意味着 b 肯定是空的,反之亦然?

最佳答案

没有。如果它们都不为空,则第一个 while 条件将为真。

第一个 while 结束后,a、b 至少有一个为空。

关于java - 这部分代码会在归并排序中执行吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36667152/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com