Recursion 理解递归(将其应用于冒泡排序)

Recursion 理解递归(将其应用于冒泡排序),recursion,Recursion,我正试图弄明白如何在程序中使用递归。我理解递归在诸如“阶乘”之类的经典示例中是如何工作的,但我不知道如何将其应用于我自己 我从将迭代冒泡排序代码转换为递归代码开始。。。 我已经在网上搜索过了。。。。但我无法找到令人信服的解决方案/解释 冒泡排序的迭代代码示例如下: 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],ar

我正试图弄明白如何在程序中使用递归。我理解递归在诸如“阶乘”之类的经典示例中是如何工作的,但我不知道如何将其应用于我自己

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

冒泡排序的迭代代码示例如下:

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:1到n) 对于(j:1到n-1) 如果(arr[j+1]>arr[j]) 掉期(arr[j+1],arr[j]);
如果有人能给我一个关于如何进行的提示,我会觉得很有帮助。

我不确定Bubblesort是否是一个练习递归的好算法。将其转换为递归将非常难看,因为它是一个嵌套循环。它看起来像这样:

function pass(i,j,n,arr)
{
  if(arr[i]>arr(j))
    swap(arr[i],arr[j]);

  if(j==n)
  {
    j=0;
    i=i+1;
  }
  if(i==n+1)
    return arr;

  return pass(i,j+1,n,arr);
}
循环也是一样,只是定义的时间更长,占用的内存更多

您应该尝试实现快速排序。它需要递归,而且在大多数情况下比BubbleSort快得多。大多数平台已经实现了它,所以您不必自己编写它,但是了解它是如何工作的很好,这有助于理解递归

如果需要,还可以尝试使用递归解决此问题:

您有一个数字表NxM和一个起始坐标(位置)。这是一个^旅行者^的位置。旅行者可以前往一个相邻的单元(右、左、上或下),该单元的编号小于他所在的单元。您必须编写一个程序来计算旅行者在这些约束条件下可以通过的最长路径。使用random生成数组,或手动生成。递归是一种基于归纳证明的设计技术。考虑您的问题的一个或多个基本(简单)案例,以及使问题更接近基本案例问题的一个或多个方法。然后,在算法的每个步骤中,要么识别完成(并适当处理基本情况),要么使问题稍微接近基本情况

冒泡排序只是观察结果的一个应用,即排序后的数组中所有相邻的元素对都是有序的。递归定义,其工作原理如下:

  • 基本情况:有一个大小为1(或更小)的数组需要排序。当然,已经分类了
  • 感应情况:将最大的元素气泡到阵列顶部。现在有一个小一点的数组要排序,它可以
  • 你可以用你选择的编程语言来写这个想法,然后你就得到了冒泡排序。哦,但你必须定义“冒泡最大元素”的含义。这是递归设计的另一个机会。不过,我想你明白了

    更快的排序主要基于观察你如何在更少的工作中更接近目标。例如,快速排序依赖于这样一个概念:如果一个数组被排序,那么就有一些元素P,小于P的所有元素都在P的左边,大于P的所有元素都在P的右边。如果您可以在数组上建立该属性,并选择P,那么您可以在每个步骤中将问题大致减半,而不是简单地按一个进行排序。

    public void sort(int[]arr,int first,int last){
    
    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;
    }
    
    if(first0){ if(arr[first]>arr[first+1]){ int temp=arr[第一]; arr[first]=arr[first+1]; arr[第一+1]=温度; } 排序(arr,第一个+1,最后一个); 排序(arr、first、last-1); } 其他的 返回; }

    晚了2年,但可能对某人有用,因为我发现这个问题是第一个示例之一,我想提供一种执行递归的其他方法,不需要额外的参数:

    function bubblesort (input: some integer array):
      if input is empty:
        return input
      else:
        do one bubble sort run for input
        subarray = bubblesort(unsorted part of input)
        return subarray append sorted part of input
    
    这样,我们将为每个调用对整个数组进行分段排序

    它为什么有效?因为每次冒泡排序都会运行,所以我们至少会将最大的元素放在最右边的索引中。
    我们知道,直到最后一次交换之前的所有元素都处于未知状态,最后一次交换之后的所有元素都已排序

    可以在那里找到Java实现(数组/列表参数修改/不修改):

    \include
    #包括
    无效排序(int*arr,int first,int last){
    if(first0){
    if(arr[first]>arr[first+1]){
    int temp=arr[第一];
    arr[first]=arr[first+1];
    arr[第一+1]=温度;
    }
    排序(arr,第一个+1,最后一个);
    排序(arr、first、last-1);
    }
    其他的
    返回;
    }
    内部主(空){
    int data[]={3,5,6,2,1,10,4};
    int len=sizeof(数据)/sizeof(int);
    int i=0;
    排序(数据,0,len-1);
    
    对于(i=0;i这是我的答案。它基本上与VladimFromUa的答案(冒泡排序的递归变体)相同,但不是执行固定次数的运行,而是仅在检测到阵列在上一次运行时被重新排序时才执行额外的运行

    另外两个不同点如下:

    1.通过在递归调用中偏移数组的地址,删除了索引数组中起始点的参数。 2.Vlad中的“if(first0)”或代码中的“if(-p_length==1)”检查最好在递归调用之前执行,这将导致数组长度为1,因为它在堆栈上少调用一次

    为了方便起见,我添加了一些代码从命令行读取输入,并打印未排序和排序的数组

    #include <stdio.h>
    #include <stdlib.h>
    #include <assert.h>
    
    typedef enum { FALSE, TRUE } boolean_t;
    
    void
    swap_int(int *a, int *b) {
    
        int temp = *a;
    
        *a = *b;
        *b = temp;
    }
    
    boolean_t
    sort_array(int p_array[], int p_length) {
    
        boolean_t result;
    
        if (p_array[0] > p_array[1]) {
            swap_int(p_array, p_array + 1);
            result = TRUE;
        } else {
            result = FALSE;
        }
    
        if (--p_length == 1) {
            return result;
        }
    
        result |= sort_array(p_array + 1, p_length);
    
        if (result) {
            sort_array(p_array, p_length);
        }
    
        return result;
    }
    
    void
    print_array_int(int p_array[], int p_length) {
    
        int n;
    
        for (n = 0; n < p_length - 1; n++) {
            printf("%d, ", p_array[n]);
        }
    
        printf("%d\n", p_array[n]);
    }
    
    int
    main(int argc, char **argv) {
    
        int *array;
        int array_length = argc - 1;
        int n;
    
        array = malloc(array_length * sizeof(*array));
    
        for (n = 0; n < array_length; n++) {
            sscanf(argv[n + 1], "%d", array + n);
        }
    
        printf("\nUnsorted array:\n");
        print_array_int(array, array_length);
        sort_array(array, array_length);
        printf("\nSorted array:\n");
        print_array_int(array, array_length);
    
    return 0;
    }
    
    #包括
    #包括
    #包括
    typedef枚举{FALSE,TRUE}布尔值;
    无效的
    交换int(int*a,int*b){
    int temp=*a;
    *a=*b;
    *b=温度;
    }
    布尔值
    排序数组(int p_数组[],int p_长度){
    布尔结果;
    if(p_数组[0]>p_数组[1]){
    交换整数(p_数组,p_数组+1);
    结果=真;
    }否则{
    结果=假;
    }
    如果(--p_长度==1){
    返回结果;
    }
    结果|=排序数组(p_数组+1,p_长度);
    如果(结果){
    
    #include <stdio.h>
    #include <stdlib.h>
    #include <assert.h>
    
    typedef enum { FALSE, TRUE } boolean_t;
    
    void
    swap_int(int *a, int *b) {
    
        int temp = *a;
    
        *a = *b;
        *b = temp;
    }
    
    boolean_t
    sort_array(int p_array[], int p_length) {
    
        boolean_t result;
    
        if (p_array[0] > p_array[1]) {
            swap_int(p_array, p_array + 1);
            result = TRUE;
        } else {
            result = FALSE;
        }
    
        if (--p_length == 1) {
            return result;
        }
    
        result |= sort_array(p_array + 1, p_length);
    
        if (result) {
            sort_array(p_array, p_length);
        }
    
        return result;
    }
    
    void
    print_array_int(int p_array[], int p_length) {
    
        int n;
    
        for (n = 0; n < p_length - 1; n++) {
            printf("%d, ", p_array[n]);
        }
    
        printf("%d\n", p_array[n]);
    }
    
    int
    main(int argc, char **argv) {
    
        int *array;
        int array_length = argc - 1;
        int n;
    
        array = malloc(array_length * sizeof(*array));
    
        for (n = 0; n < array_length; n++) {
            sscanf(argv[n + 1], "%d", array + n);
        }
    
        printf("\nUnsorted array:\n");
        print_array_int(array, array_length);
        sort_array(array, array_length);
        printf("\nSorted array:\n");
        print_array_int(array, array_length);
    
    return 0;
    }
    
    function bubbleSortRecursive(array, index1, index2) {
        //define index1 and index2 if user doesn't pass them in
        index1 = typeof index1 == "undefined" ? 0 : index1;
        index2 = typeof index2 == "undefined" ? array.length : index2;
    
        if (index1 > index2) {
            return array;
        } else if (index1 == index2 - 1) {
            return bubbleSortRecursive(array, 0, index2 - 1);
        } else if (array[index1] > array[index1 + 1]) {
            //bubble the larger value towards the end of the array
            var temp = array[index1];
            array[index1] = array[index1 + 1];
            array[index1+1] = temp;
            return bubbleSortRecursive(array, index1 + 1, index2);
        } else {
            return bubbleSortRecursive(array, index1 + 1, index2);
        }
    }
    
    static void recursive_bubble_sort(int[] Arr, int l)
    {// 'Arr' is the array where 'l' is the length of the array
    
        if (l == 0) {
           return;
        }
    
        for (int j = 0; j < l - 1; j++) {
            if (Arr[j] > Arr[j + 1]) {
                swap(Arr[j], Arr[j + 1]);
            }
        }
    
        recursive_bubble_sort(Arr, l - 1);
    }
    
    Bubble sort: recursive and efficient
    
    public static void bubbleSort(int[] ele, int counter, int index) {
                int temp=-1;
                if (counter < ele.length) {
                    if (index < ele.length - 1) {
                        if (ele[index] > ele[index+1]) {
                            ele[index] += ele[index+1];
                            ele[index+1] = ele[index] - ele[index+1];
                            ele[index] = ele[index] - ele[index+1];
                            temp = ele[index];
                        }
                        bubbleSort(ele, counter, index+1);
                        //temp = sortedIndex;
                        return;
                    }
                    if(counter == ele.length-1 && temp==-1){
                        return;
                    }
                    bubbleSort(ele, counter+1, 0);
                }
    
            }
    
    package recursive.bubble;
    
    public class RecursiveBubble {
    
        public static boolean sort(int []arr){
            if(!bubbleSorted(arr, 0)){
                return sort(arr);
            }
            return true;
        }
        public static boolean bubbleSorted(int []a,int index){    
            if(a.length<2){
                return true;
            }
            if(index==a.length-2){
                if(a[index+1]<a[index]){
                    swap(a,index,index+1);
                    return false;
                }
                return true;
            }
            boolean isSorted=false;
            if(a[index]<=a[index+1]){
                isSorted=true;
            }else{
                swap(a,index,index+1);
            }
            return isSorted && bubbleSorted(a, index+1);
        }
        private static void swap(int[] a, int index, int i) {
            int tmp=a[index];
            a[index]=a[i];
            a[i]=tmp;
        }
        public static void main(String[] args) {
            int []a={4,5,6,2,2,3,9,1,8};
            if(sort(a))
            for (int i = 0; i < a.length; i++) {
                System.out.println(a[i]);
            }
        }
    }
    
    def bubble_sort(l):
        for i, num in enumerate(l):
            try:
                if l[i+1] < num:
                    l[i] = l[i+1]
                    l[i+1] = num
                    bubble_sort(l)
            except IndexError:
                pass
        return l
    
    #include <stdio.h>
    void bubbleSort(int *,int ,int ,int );
    void swap(int *, int *);
    void printArray(int *,int);
    
    int main()
    {
        int n,c;
    
        printf("Enter number of elements\n");
        scanf("%d", &n);
    
        int array[n];
    
        printf("Enter %d integers\n", n);
    
        for (c = 0; c < n; c++)
            scanf("%d", &array[c]);
    
        printf("Before Sorting:\n");
        printArray(array,n);
    
        bubbleSort(array,0,0,n);
    
        printf("After Soring:\n");
        printArray(array,n);
    
     }
    
     void bubbleSort(int *array,int i,int j,int n)
     {
         if(j==n-i-1)
         {
             i = i+1;
             j = 0;
         }
         if(i==n-1)
             return;
    
         if(array[j]>array[j+1])
             swap(&array[j],&array[j+1]);
    
         j++;
         bubbleSort(array,i,j,n);
     }
    
     void swap(int *p,int *q)
     {
         int t = *q  ;
         *q = *p;
         *p = t;
     }
    
     void printArray(int *array,int n)
     {
         int c=0;
         for (c = 0; c < n; c++)
            printf("%d ", array[c]);
        printf("\n");
     }
    
    def sort(initial: List[Int], result: List[Int] = Nil): List[Int] = {
    
      def getBiggest(list: List[Int], rest: List[Int] = Nil): (List[Int], Int) = list match {
        case x1 :: x2 :: tail =>
          if(x1 > x2)
            getBiggest(x1 :: tail, x2 :: rest)
          else
            getBiggest(x2 :: tail, x1 :: rest)
        case x :: Nil => (rest, x)
      }
    
      initial match {
        case _ :: _ :: _ =>
          getBiggest(initial) match {
            case (rest, biggest) => sort(rest, biggest :: result)
          }
        case x :: Nil => x :: result
        case Nil => Nil
      }
    }
    
    package com.examplehub.sorts;
    
    public class BubbleSortRecursion implements Sort {
      @Override
      public void sort(int[] numbers) {
        sortRecursion(numbers, numbers.length);
      }
    
      /**
       * BubbleSort algorithm implements using recursion.
       *
       * @param numbers the numbers to be sorted.
       * @param length the length of numbers.
       */
      public void sortRecursion(int[] numbers, int length) {
        boolean swapped = false;
        for (int i = 0; i < length - 1; ++i) {
          if (numbers[i] > numbers[i + 1]) {
            int temp = numbers[i];
            numbers[i] = numbers[i + 1];
            numbers[i + 1] = temp;
            swapped = true;
          }
        }
        if (!swapped) {
          return;
        }
        sortRecursion(numbers, length - 1);
      }
    
      @Override
      public <T extends Comparable<T>> void sort(T[] array) {
        sortRecursion(array, array.length);
      }
    
      /**
       * Generic BubbleSort algorithm implements using recursion.
       *
       * @param array the array to be sorted.
       * @param length the length of array.
       * @param <T> the class of the objects in the array.
       */
      public <T extends Comparable<T>> void sortRecursion(T[] array, int length) {
        boolean swapped = false;
        for (int i = 0; i < length - 1; ++i) {
          if (array[i].compareTo(array[i + 1]) > 0) {
            T temp = array[i];
            array[i] = array[i + 1];
            array[i + 1] = temp;
            swapped = true;
          }
        }
        if (!swapped) {
          return;
        }
        sortRecursion(array, length - 1);
      }
    }
    
    // BubbleSortRecursive ...
    func BubbleSortRecursive(data []int) {
    
        i := 0
        max := len(data)
    
        bubbleSortRecursive(data, i, max)
    }
    
    func bubbleSortRecursive(data []int, i, max int) {
    
        fmt.Printf("data = %v, i = %v, max = %v\n", data, i, max)
    
        if i == max-1 {
            max--
            i = 0
        }
    
        if i < max-1 {
            if data[i] > data[i+1] {
                data[i], data[i+1] = data[i+1], data[i]
            }
            bubbleSortRecursive(data, i+1, max)
        }
    }