Java中的合并排序
我必须用 Java 编写一个合并排序函数。没问题。嗯,有一点,但我还是挺过来了。然后是我没有得到的后续问题。
问题:给定一个数组 A[][]
,其中 A[i][0]
是一个 float
且 A[i ][1]
是一个非负 int
,给出值 A[i][0]
的重数(这里想象一个已折叠的大向量通过组合重复的条目并记录组合的数量),编写一个版本返回 B[][]
的合并排序,其中 B[i][0]
B[i+1][0]
对于所有 i
。
有什么想法吗?我能做的最好的事情就是合并排序,然后将相等的分组,但显然你可以一步完成这一切。
I had to write a merge sort function in Java. No problem. Well, a little, but I got through it. Then the follow up question I didn't get.
Question: Given an array A[][]
such that A[i][0]
is a float
and A[i][1]
is a nonnegative int
giving the multiplicity of the value A[i][0]
(here think of a big vector that's been collapsed down by combining repeated entries and recording how many got combined), write a version of merge sort that returns B[][]
where B[i][0] < B[i+1][0]
for all i
.
Any ideas? The best I could do was merge sort and then group the equal ones, but apparently you can do it all in one step.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
奇怪的问题......在这些数组中使用不同的类型是丑陋的(个人观点)。
但是,最有用的事情是使用
比较器
。这样您就可以使用您想要的任何属性进行排序。
您最终会得到类似
void merge(A[] arr, Comparator comp)
的签名。顺便说一句,排序的 Java 实现很像这样。
要解决您的问题,您可以致电:
Strage question... and using different types in these arrays is just ugly (personal point of view).
However, the most useful thing to do, is to rewrite your merge function with a
Comparator
.This way you can sort using whatever property you want.
You would end up with a signature like
void merge(A[] arr, Comparator<? super A> comp)
.By the way, the Java implementation of sort is a lot like this.
To solve your question you would call: