理解递归(将其应用于冒泡排序)
我想弄清楚如何在程序中使用递归。我了解递归在“阶乘”等经典示例中的工作原理,但不确定如何自己应用它......
我开始将迭代冒泡排序代码转换为递归代码...... 我在网上搜索了相同的内容......但无法找到令人信服的解决方案/解释......
冒泡排序的示例迭代代码是:
arr[n]->包含要排序的元素 (1..n) 的数组
for(i:1 to n) for(j:1 to n-1) if(arr[j+1]>arr[j]) swap(arr[j+1],arr[j]);
如果有人能给出有关如何进行的提示,将会很有帮助...
I am trying to figure out how to use recursion in programs. I understand how recursion works in classical examples like "factorial", but am not sure how to apply it on my own...
I am starting out with converting an iterative bubble sort code into a recursive code...
I have searched over the net for the same.... but am not able to find a convincing solution/explanation..
Example iterative code for bubble sort is:
arr[n]-> array with elements (1..n) which is to be sorted
for(i:1 to n) for(j:1 to n-1) if(arr[j+1]>arr[j]) swap(arr[j+1],arr[j]);
Would feel helpful if someone could give a hint about how to go about...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(17)
迟了两年,但也许对某人有用
Late for 2 years, but maybe it will useful to someone
我不确定冒泡排序是否是练习递归的好算法。将其转换为递归会非常难看,因为它是一个嵌套循环。它看起来像这样:
它是相同的 for 循环,只是定义时间更长,使用更多内存。
相反,您应该尝试实现快速排序。它需要递归,并且在大多数情况下比冒泡排序快得多。大多数平台已经实现了它,因此您不必自己编写它,但了解它是如何工作的很有好处,并且有助于理解递归。
如果您愿意,您也可以尝试使用递归来解决此问题:
您有一个 NxM 数字表和一个起始坐标(位置)。这是^旅行者^的立场。旅行者可以前往相邻的单元格(右、左、上或下),该单元格的编号小于他所在的单元格的编号。您必须编写一个程序来计算旅行者在这些约束下可以通过的最长路径。使用随机生成数组,或手动生成。
I am not sure whether Bubblesort is a good algorithm to practice recursion on. It would be quite ugly to convert it to recursion because it's a nested cycle. It would look something like this:
It's the same for loop, only longer to define, using a lot more memory.
You should instead try to implement QuickSort. It needs recursion, and it's a lot faster in most cases than BubbleSort. Most platforms implemented it already, so you don't have to write it yourself, but it's good to know how it works, and it helps understand recursion.
If you want you might also try to solve this problem using recursion:
You have a table NxM of numbers, and a starting coordinate (position). It's a ^travellers^ position. The traveller can travel to an adjacent cell (right, left, up or down) which has a smaller number than the one he's on. You must write a program that computes the longest path the traveller can pass under these constraints. Use random to generate the array, or generate it manually.
递归是一种基于归纳证明的设计技术。考虑您的问题的一个或多个基本(简单)案例,以及使问题更接近基本案例问题的一种或多种方法。然后,在算法的每个步骤中,您要么认识到完成(并适当地处理基本情况),要么使问题稍微接近基本情况。
冒泡排序只是观察排序数组按顺序排列所有相邻元素对的观察的应用。以递归方式定义,其工作原理如下:
您可以用您选择的编程语言编写这个想法,然后就可以进行冒泡排序。哦,但是你必须定义“冒泡最大元素”的含义。嗯,这是递归设计的另一个机会。不过,我想你已经明白了。
更快的排序主要基于对如何以更少的工作更接近目标的观察。例如,快速排序依赖于这样的概念:如果一个数组已排序,则存在某个元素 P,并且所有小于 P 的元素都位于 P 的左侧,所有大于 P 的元素都位于 P 的右侧。如果您可以在数组上建立该属性,并选择 P,那么您可以在每一步将问题大致减半,而不是简单地减半。
Recursion is a design technique based on inductive proofs. Considers one or more base (simple) case(s) for your problem, and one or more ways to move the problem closer to being a base-case problem. Then, at each step of the algorithm, you either recognize completion (and deal appropriately with a base case) make the problem slightly closer to being a base case.
Bubble sort is just an application of the observation that a sorted array has all adjacent pairs of elements in order. Defined recursively, it works like:
You can write that very idea in the programming language of your choice, and you get bubble sort. Oh, but you have to define what it means to "bubble the largest element". Well, that's another opportunity for recursive design. I think you get the idea, though.
Faster sorts are mostly based on observations about how you get closer to the goal in less work. Quick sort, for instance, relies on the notion that, if an array is sorted, then there is some element P, and all elements less than P are to P's left, and all elements more than P are to P's right. If you can establish that property on an array, and also pick P, then you can cut the problem roughly in half at each step instead of simply by one.
这是 javascript 中的递归冒泡排序:
函数内的前两行允许用户调用bubbleSortRecursive(array),函数将定义index1和index2
Here is a recursive bubblesort in javascript:
The first 2 lines inside the function allow the user to call
bubbleSortRecursive(array)
and the function will define theindex1
andindex2
这是使用
冒泡排序
对数组进行递归
排序的另一种简单方法。对于递归解决方案,必须更新长度,以便函数始终适用于数组中的其余项目。
Here is another easy way to sort your array
recursively
usingBubble-Sort
.For recursive solution, the length must be updated so function always works with the remaining items from array.
因为我发现这个问题是第一个例子,所以我想提供另一种方法来进行递归,而不需要额外的参数:
通过这种方式,我们将为每次调用对整个数组进行分段排序。
为什么它有效?因为每次冒泡排序运行,我们都会至少将最大的元素放入最右边的索引。
我们知道,直到最后一次交换的所有元素都处于未知状态,所有在最后一次交换之后都已排序。
Java 中的实现(数组/列表参数修改/不修改)可以在那里找到: https://codereview.stackexchange.com/questions/24006/recursive-bubble-sort-in-java/24133#24133
Because I found this question as one of the first examples, I would like to provide an other way to do the recursion, without additional arguments:
In this way, we will sort the whole array piecewise for each call.
Why does it work? Because every bubble sort run, we will put at least the largest element to the rightmost index.
We know that all elements until the last swap are in unknown state, all after the last swap are sorted.
Implementations in Java (array/list argument-modifying/not) could be found there: https://codereview.stackexchange.com/questions/24006/recursive-bubble-sort-in-java/24133#24133
这是我的答案。它本质上与 VladimFromUa 的答案(冒泡排序的递归变体)相同,但不是执行固定数量的运行,而是仅在检测到数组在上一次运行中重新排序时才执行额外的运行。
另外两个差异如下:
1. 通过在递归调用中偏移数组地址,删除了数组中索引起始点的参数。0)”或我的代码中的“if (--p_length == 1)”最好在递归调用之前执行,这会导致数组长度为 1,因为它在堆栈上少了一次调用。
2.Vlad 中的检查“if(first
为了方便起见,我添加了一些代码来从命令行读取输入并打印未排序和排序的数组。
Here's my answer. It's essentially the same as VladimFromUa's answer (a recursive variant of bubble sort) but instead of doing a fixed number of runs, additional runs are only performed if it's detected that the array was reordered on the previous run.
Another couple of differences are below:
1.The parameter indexing the starting point in the array has been dropped by offsetting the address of the array in recursive calls.
2.The check "if(first < last && last > 0)" in Vlad's or "if (--p_length == 1)" in my code is better performed before the recursive call that would result in the array length being 1, since it is one less call on the stack.
I added some code to read the input from the command line and print both the unsorted and sorted arrays, for convenience.
这种解决方案怎么样:
How about this kind of solution:
这是scala函数代码。一切都是一成不变的。这就是尾递归。所以堆栈应该没问题
Here is scala functional code. Everything is immutable. And this is tail recursion. So the stack should be fine
这是另一个 javascript 递归版本,其中包含一些 es6/7 语法,例如默认参数:
Here's another javascript recursion version with some es6/7 syntax such as default argument parameters:
来源
source from
戈兰:
Golang:
希望这有帮助。
Hope this helps.