仅以数组作为输入的递归排序
我已经编写了一些简短的递归程序,现在正在递归地进行排序。到目前为止我一直在使用 2 个输入:数组和索引。有没有一种只需要数组作为输入的递归排序方法?我认为冒泡排序可以解决这个问题,但它也使用索引来跟踪位置。
如果有人想知道,我有一个硬件来进行递归排序(我已经这样做了,使用数组和索引),这只是为了看看是否可以在没有索引的情况下完成它。
I've written a few short recursive programs, and am now doing sorting recursively. I've been using 2 inputs up to now, the array, and an index. Is there a recursive method for sorting that only needs an array as input? I was thinking Bubble Sort would work for this, but that also uses an index to keep track of position.
And in case anyone wants to know, I had a HW to make a recursive sort (which I already did, using an array and index), this is just to see if its possible to do it without the index.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我相信可以仅使用数组作为参数来执行递归合并排序:
http://en.wikipedia.org/wiki/Merge_sort
编辑:
我想你可以像这样跳过索引:
这不是完美的冒泡排序,因为起始索引始终为零。复杂度仍然是O(n^2)。如果您愿意克隆数组(并浪费大量内存),那么您可以替换
为:
然后,这是一种仅以数组作为参数实现递归冒泡排序的有效但浪费的方法。
I believe a recursive merge sort can be performed with only an array as a parameter:
http://en.wikipedia.org/wiki/Merge_sort
Edit:
I guess you could skip the index like this:
This is not a perfect bubble-sort as the starting index is always zero. The complexity is still O(n^2). If you're willing to clone the array (and waste a lot of memory) then you can replace
With:
Then it's a valid, though wasteful, way of achieving a recursive bubble sort with only an array as the parameter.