了解递归(将其应用于冒泡排序) [英] Understanding Recursion (applying it on Bubble Sort)

查看:40
本文介绍了了解递归(将其应用于冒泡排序)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想弄清楚如何在程序中使用递归.我了解递归在诸如阶乘"之类的经典示例中是如何工作的,但我不确定如何自行应用它...

我开始将迭代冒泡排序代码转换为递归代码...我已经在网上搜索了相同的内容......但我无法找到令人信服的解决方案/解释..

冒泡排序的示例迭代代码是:

arr[n]-> 包含要排序的元素 (1..n) 的数组

<前>for(i:1 到 n)for(j:1 到 n-1)if(arr[j+1]>arr[j])交换(arr[j+1],arr[j]);

如果有人可以提供有关如何去做的提示,我会觉得很有帮助...

解决方案

public void sort(int[] arr, int first, int last){if(first < last && last > 0){if(arr[first] > arr[first+1]){int temp = arr[first];arr[first] = arr[first+1];arr[first+1] = 温度;}排序(arr,第一个+ 1,最后一个);sort(arr, first, last-1);}别的返回;}

迟到 2 年,但也许对某人有用

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...

解决方案

public void sort(int[] arr, int first, int last){

    if(first < last && last > 0){
        if(arr[first] > arr[first+1]){
            int temp = arr[first];
            arr[first] = arr[first+1];
            arr[first+1] = temp;
        }
        sort(arr, first+1, last);
        sort(arr, first, last-1);
    }
    else
        return;
}

Late for 2 years, but maybe it will useful to someone

这篇关于了解递归(将其应用于冒泡排序)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆