C language recursive algorithm to achieve classic examples

1. Recursion

1. What is recursion

Recursion is a programming technique that solves a problem by repeatedly calling itself inside a function. When a program calls itself, it's called a recursive call. Recursion can help simplify the implementation and understanding of certain algorithms. During recursion, each call saves some data on the stack, which cannot be processed and popped until the end of the recursion.

Recursion usually has two parts: the base case and the recursive case. The basic situation is to judge whether recursion is required before the function is executed, and return the result directly if not. A recursive case is when a function needs to recurse, it calls itself, but the parameters passed in are usually varied so that the base case is eventually reached and the recursion ends.

Although recursion can make the code more concise, it should be noted that in some cases, it may cause performance problems or stack overflow problems. Therefore, when writing recursive code, factors such as the boundary conditions of the algorithm and the depth of recursion need to be carefully considered.

2. Recursive function

A recursive function is a function that calls itself within its definition. Typically, a recursive function consists of two parts: the base case and the recursive case.

The basic case refers to the condition that needs to be judged whether the recursion needs to be terminated in the recursive function. When this condition is met, the recursion stops.

A recursive case is when a recursive function needs to call itself. The parameters of the function should be different on each call so that the base case is eventually reached and the recursion stops.

Recursive functions are often used to process tree structures, graph structures, or other types of nested structured data. For example, recursive functions can be used to find a value in a binary tree.

3. Description

Although the recursive algorithm is relatively simple, it is a programming idea, and it is very applicable when solving some problems. And it is generally used as a tool to be used together with other ideas. It is the simplest algorithm in C language data structure and algorithm, here are a few examples to learn to use it.

2. Fibonacci sequence

1. Problem description

The Fibonacci sequence is a classic mathematical problem, starting with 0 and 1, and each subsequent item is the sum of the previous two. In other words, the first few numbers of the Fibonacci sequence are: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34...and so on.

The Fibonacci sequence has many applications in nature, such as the arrangement of leaves in plants, the structure of honeycombs, and so on. In addition, in the field of computer science, the Fibonacci sequence also has a wide range of applications, such as in sorting algorithms, cryptography and other fields.

The general term formula of the Fibonacci sequence is: F(n) = F(n-1) + F(n-2), where F(0)=0 and F(1)=1. According to this formula, recursive functions or loop statements can be used to find the nth item of the Fibonacci sequence.

2. Ideas

Such a sequence that can be used to find the general term formula is our typical recursive function application. The general term formula can be defined as a function, and its first value is generally the exit of our recursive function. The exit of the so-called recursive function is the sign to end the recursion.

Now that we have cleared our minds, let's use code to find the nth item of the Fibonacci sequence:

3. C language code

#include <stdio.h>

int fibonacci(int n) {
    
    
    if (n == 0)
        return 0;
    else if (n == 1)
        return 1;
    else
        return fibonacci(n - 1) + fibonacci(n - 2);
}

int main() {
    
    
    int num, i;
    printf("Enter the number of terms: ");
    scanf("%d", &num);
    printf("Fibonacci series terms are:\n");
    for (i = 0; i < num; i++) {
    
    
        printf("%d ", fibonacci(i));
    }
    printf("\n");
    return 0;
}

3. Tower of Hanoi

1. Problem description

The main materials for this problem include three pillars of the same height and discs of different sizes and colors. The three pillars are the starting pillar A, the auxiliary pillar B and the goal pillar C.

**Rules of operation:** Only one plate can be moved at a time, and the large plate is always on the bottom and the small plate is on top of the three rods during the movement process. The plate can be placed on any rod during the operation.

wUhV.jpg

2. Analysis

The Tower of Hanoi is a classic recursive problem that involves moving a set of disks of different sizes from one pillar to another. The following is the specific process of the Tower of Hanoi:

  1. Move all discs from the starting post except the bottom one to the middle post.
  2. Move the bottom disc from the starting peg to the goal peg.
  3. Move all but the bottom disc on the middle post to the target post.

When completing these three steps, the following rules need to be followed:

  1. Only one disc can be moved at a time.
  2. A large disk cannot be placed on top of a small disk.

By recursively calling the above steps, all disks can be moved from the start peg to the goal peg. Since each recursion moves a disc from the starting peg to the target peg, each disc is moved at most once, so a total of 2^n - 1 moves are required (n represents the number of discs).

3. C language code

#include <stdio.h>

void hanoi(int n, char A, char B, char C) {
    
    
    if (n == 1) {
    
    
        printf("Move disk 1 from %c to %c\n", A, C);
    } else {
    
    
        hanoi(n-1, A, C, B);
        printf("Move disk %d from %c to %c\n", n, A, C);
        hanoi(n-1, B, A, C);
    }
}

int main() {
    
    
    int n = 3; // 将3个盘子从A移动到C
    hanoi(n, 'A', 'B', 'C');
    return 0;
}

4. Subset problem

1. Problem description

Subset problem (Subset): Given a set S containing n elements, find all subsets of S. It can be implemented using recursion.

2. Thinking analysis

The subset problem is a basic combinatorial problem that involves selecting elements from a given set to form a new set. This problem is very common in computer science and mathematics, and solving subset problems can help us better understand combinatorial problems and algorithm design.

The following is a simple thought analysis:

  1. First, we need to decide how to represent collections. In most programming languages, collections are usually represented by arrays or lists.

  2. Next, we need to consider how to generate all possible subsets. A common approach is to use a recursive algorithm.

  3. For recursive algorithms, we need to consider the following:

    a. Base case: When the set is empty, there is only one empty set.

    b. Recursive case: For a non-empty collection, we can choose to include the first element in the subset or not, and then recursively process the remaining elements.

  4. During the recursion, we need to maintain a list of the current subset and add it to the result set after each recursion ends.

  5. Finally, we can return the result set, which contains all possible subsets of the original set.

It should be noted that since the solution space of the subset problem is very large, in practical applications, it needs to be optimized according to specific scenarios to reduce time and space complexity.

3. C language code

The following is a sample code to implement the subset problem recursively in C language:

#include <stdio.h>

void subset(int set[], int subset[], int n, int k, int start, int curr){
    
    
    if (curr == k) {
    
    
        printf("{");
        for (int i = 0; i < k; i++) {
    
    
            printf("%d ", subset[i]);
        }
        printf("}\n");
        return;
    }
    for (int i = start; i < n; i++){
    
    
        subset[curr] = set[i];
        subset(set, subset, n, k, i+1, curr+1);
    }
}

int main() {
    
    
    int set[] = {
    
    1, 2, 3};
    int n = sizeof(set)/sizeof(set[0]);
    int subset[n];
    for (int i = 0; i <= n; i++) {
    
    
        subset(set, subset, n, i, 0, 0);
    }
    return 0;
}

In this code, subsetthe function is implemented using recursion. Among them, setrepresents the original collection, subsetrepresents the current subset, nrepresents the size of the original collection, krepresents the size of the current subset, startrepresents the starting position of the traversal, and currrepresents the number of elements in the current subset.

In the function, first judge whether the current subset has reached the target size k, and if so, output the subset and return to the previous level of recursion. Otherwise, loop through the original collection from the starting position of the traversal, add elements to the current subset in turn, and recursively process the remaining elements.

In mainthe function , we iterate over all possible subset sizes and call subsetthe function to solve. The final results are output to standard output in turn.

Five. Merge sort

1. Problem description and analysis

Merge Sort (Merge Sort) is an efficient sorting algorithm based on the divide-and-conquer idea. By recursively splitting the array to be sorted into two sub-arrays, sorting each sub-array, and then merging the two sorted sub-arrays into A sorted array, and finally get the whole array sorted.

Specifically, the process of merge sort can be divided into three steps:

  1. Split: Divide the array to be sorted from the middle position into left and right sub-arrays, recursively split the left and right sub-arrays until each sub-array contains only one element.
  2. Merge: Merge two sorted subarrays into one sorted array until all subarrays are merged into a complete sorted array.
  3. Returns: Returns the sorted array.

2. C language code

The following is the code to implement merge sort recursively in C language:

#include <stdio.h>
#include <stdlib.h>

void merge(int *arr, int l, int m, int r) {
    
    
    int i, j, k;
    int n1 = m - l + 1;
    int n2 = r - m;

    int L[n1], R[n2];

    for (i = 0; i < n1; i++)
        L[i] = arr[l + i];
    for (j = 0; j < n2; j++)
        R[j] = arr[m + 1 + j];

    i = 0;
    j = 0;
    k = l;
    while (i < n1 && j < n2) {
    
    
        if (L[i] <= R[j]) {
    
    
            arr[k] = L[i];
            i++;
        } else {
    
    
            arr[k] = R[j];
            j++;
        }
        k++;
    }

    while (i < n1) {
    
    
        arr[k] = L[i];
        i++;
        k++;
    }

    while (j < n2) {
    
    
        arr[k] = R[j];
        j++;
        k++;
    }
}

void mergeSort(int *arr, int l, int r) {
    
    
    if (l < r) {
    
    
        int m = l + (r - l) / 2;

        mergeSort(arr, l, m);
        mergeSort(arr, m + 1, r);

        merge(arr, l, m, r);
    }
}

int main() {
    
    
    int arr[] = {
    
    38, 27, 43, 3, 9, 82, 10};
    int n = sizeof(arr) / sizeof(arr[0]);
    
    mergeSort(arr, 0, n - 1);

    for (int i = 0; i < n; i++)
        printf("%d ", arr[i]);
    
    return 0;
}

In the above code, mergethe function is used to merge two sorted subarrays into one sorted array, and mergeSortthe function is used to recursively split and sort the subarrays.

6. Description

Rising Star Project: Data Structure and Algorithm, @西安第一感情, Creation Punch 1!

Guess you like

Origin blog.csdn.net/weixin_51496226/article/details/130759521