The recursive algorithm: description, analysis, features and examples

A modern understanding of recursion: the definition of functionality and access to it from outside and from this functionality. It is believed that recursion was born by mathematicians: calculating factorial, infinite series, fractals, continued fractions ... However, recursion can be found everywhere. Objective natural laws "consider" recursion as their main algorithm and form of expression (existence) not so much of the objects of the material world, as in general the main algorithm of motion.

recursive algorithm

People of various specialties in various fields of science and technology use the recursive algorithm f (x), where "x ~ / = f (x)". A function that calls itself is a strong solution, but the formation and understanding of this solution is, in most cases, a very difficult task.

In ancient times, recursion was used to increase the palace space. Through a system of mirrors aimed at each other, you can create stunning volumetric spatial effects. But is it so easy to understand how to set up these mirrors? And it’s even more difficult to determine where a point in space is reflected through several mirrors.

Recursion, recursive algorithms: meaning and syntax

A problem that is formulated by repeating a sequence of operations can be solved recursively. A simple algorithm (calculating a quadratic equation, a script filling a web page with information, reading a file, sending a message ...) does not require recursion.

The main differences of the algorithm, which allows a recursive solution:

  • There is an algorithm that needs to be executed several times;
  • an algorithm needs data that changes every time;
  • the algorithm does not have to be changed every time;
  • There is a final condition: the recursive algorithm is not infinite.

In the general case, it cannot be argued that single execution is a prerequisite for the absence of a reason for recursion. One cannot also require the presence of a mandatory final condition: infinite recursions have their own sphere of application.

The recursive algorithm: when a sequence of operations is performed repeatedly, on data that changes every time and gives a new result each time.

Recursion formula

The mathematical understanding of recursion and its counterpart in programming are different. Although mathematics is characterized by signs of programming, programming is mathematics of a much higher order.

recursive algorithm f

A well-written algorithm is like a mirror of the intellect of its author. The general recursion formula in programming is “f (x)”, where “x ~ / = f (x)” has at least two interpretations. Here “~” is the similarity or absence of the result, and “=” is the presence of the result of the function.

The first option: data dynamics.

  • the function "f (x)" has a recursive algorithm and is not mutable;
  • “X” and the result “f (x)” - each time have new values, the result “f (x)” is a new parameter “x” of this function.

Second option: code dynamics.

  • the f (x) function has several algorithms that refine (analyze) the data;
  • data analysis - one part of the code and the implementation of recursive algorithms that perform the desired action - the second part of the code;
  • the result of the function “f (x)” is not.

Lack of result is normal. Programming is not mathematics; here the result does not have to be present explicitly. A function executed recursively can simply do site parsing and populate the database, or create the necessary instances of objects according to the incoming input stream.

Data and Recursion

Programming recursive algorithms is not a factorial calculation in which a function receives a given each time, excellent by one in a smaller or larger way - the implementation option depends on the preference of the developer.

It doesn’t matter how to count the factorial “8!”, Moving from 0, 1, 2, ... or vice versa 8, 7, 6 ... Similarly, the calculation of a mathematical sequence, fractal or infinite series is written with a simple mathematical formula and, accordingly, an algorithm that strictly follows this formula.

Information processing is “mathematics” of a completely different order. Recursive functions and algorithms here operate with letters, words, phrases, sentences and paragraphs. Each next level uses the previous one.

The input data stream is analyzed over a wide range of conditions, but the analysis process is generally recursive. It makes no sense to write unique algorithms for all input stream options. There must be one functional. Here recursive algorithms are examples of how to form an output stream adequate to the input. This is not the result of entering the recursive algorithm, but it is the desired and necessary solution.

Abstraction, recursion and OOP

Object-oriented programming (OOP) and recursion are radically different entities, but they complement each other perfectly. Abstraction has nothing to do with recursion, but through the prism of OOP creates the possibility of implementing contextual recursion.

For example, information is being analyzed and letters, words, phrases, sentences and paragraphs are highlighted separately. Obviously, the developer will provide for the creation of instances of objects of these five types and will offer a solution to recursive algorithms at each level.

programming recursive algorithms

Meanwhile, if at the level of letters “it makes no sense to search for meaning”, then at the level of words semantics appear. You can divide the words into verbs, nouns, adverbs, prepositions ... You can go further and define the cases.

At the level of phrases, semantics are supplemented by punctuation and the logic of word combinations. At the level of sentences, a more perfect level of semantics is revealed, and the paragraph can be considered as a complete thought.

Object-oriented development predetermines the inheritance of properties and methods and suggests starting the hierarchy of objects with the creation of an absolutely abstract ancestor. Moreover, without a doubt, the analysis of each descendant will be recursive in nature and will not differ too much at the technical level in many positions (letters, words, phrases and sentences). Paragraphs, like complete thoughts, can stand out from this list, but not the essence.

It is important that the vast majority of the algorithm can be formulated at the level of the abstract ancestor, refining it at the level of each descendant with data and methods called from the abstract level. In this context, abstraction opens up new horizons for recursion.

Historical features of OOP

OOP has come to the world of programs twice, although some experts can highlight the emergence of cloud technologies and modern ideas about objects and classes as a new round in the development of IT technologies.

The terms “object” and “object” in the modern context of OOP are commonly referred to the 50s and 60s of the last century, but to associate them with 1965 and the advent of the languages ​​Simula, Lisp, Algol, Smalltalk.

In those days, programming was not particularly developed and could not adequately respond to revolutionary concepts. Before the struggle of ideas and programming styles (C / C ++ and Pascal - basically) was still far away, and the databases were just being formed conceptually.

recursion recursive algorithms

In the late 80s and early 90s, objects appeared in Pascal and everyone remembered about classes in C / C ++ - this marked a new round of interest in OOP, and it was then that tools, primarily programming languages, began to not only support object-oriented ideas, but also develop accordingly to them.

Naturally, if earlier recursive algorithms were simply functions used in the general code of the program, now recursion could become part of the properties of an object (class), which in the context of inheritance provided interesting possibilities.

Feature of modern OOP

The development of OOP initially declared objects (classes) as a combination of data and properties (methods). In fact, it was about data that has syntax and meaning. But then it was not possible to present OOP as a tool for managing real objects.

recursive functions and algorithms

OOP has become a tool for managing objects of "computer nature". A script, button, menu item, menu bar, tag in a browser window is an object. But not a machine tool, food, word, or sentence. Real objects remained beyond the scope of object-oriented programming, and computer tools acquired a new incarnation.

Due to the differences between popular programming languages, many OOP dialects have appeared. In terms of semantics, they are almost equivalent, and their orientation toward the instrumental sphere, rather than the applied one, makes it possible to take the description of real objects beyond the boundaries of algorithms and ensure their cross-platform and interlanguage “existence”.

Stacks and function call mechanisms

Mechanisms for calling functions (procedures, algorithms) require the transfer of data (parameters), returning the result, and remembering the address of the operator who should receive control after the completion of the function (procedure).

recursive algorithms examples

Usually, a stack is used for these purposes, although programming languages ​​or the programmer-developer himself can provide for a wide variety of control transfer options. Modern programming admits that a function name can be not only a parameter: it can be formed during the execution of an algorithm. An algorithm can also be created during the execution of another algorithm.

The concept of recursive algorithms, when their names and bodies can be defined at the time the task is formed (choosing the right algorithm), expands recursiveness not only on how to do something, but also who should do it. The choice of an algorithm by its “meaningful” name is promising, but creates difficulties.

Recursiveness on a multitude of functions

This is not to say that an algorithm is recursive when it calls itself and nothing more. Programming is not a dogma, but the concept of recursiveness is not an exclusive requirement to call oneself from the body of one's own algorithm.

Practical applications do not always provide a clean solution. Often, raw data should be prepared, and the result of a recursive call must be analyzed in the context of the entire task (the entire algorithm) as a whole.

In fact, not only before calling the recursive function, but also after its completion, another program can or should be called. If there are no special problems with the call: the recursive function A () calls the function B (), which does something and calls A (), then the problem immediately arises with the return of control. Having completed the recursive call, the A () function must take control in order to call B () again, which will call it again. Returning control, as it should be in order on the stack back to B (), is the wrong decision.

The programmer is not limited in the choice of parameters and can complete them with function names. In other words, the ideal solution is to pass the name B () to A () and let A () itself make a call to B (). In this case, there will be no problems with returning control, and the implementation of the recursive algorithm will be more transparent.

Understanding and level of recursion

The problem of developing recursive algorithms is that you need to have an idea of ​​the dynamics of the process. When using recursion in methods of objects, especially at the level of an abstract ancestor, a problem arises of understanding one's own algorithm in the context of its execution time.

recursive algorithm solution

Currently, there are no restrictions on the level of nesting of functions and the capacity of the stack in call mechanisms, but there is a problem of understanding: at what point in time what level of data or what exactly place in the general algorithm made a call to a recursive function and on how many calls to itself it is located.

Existing debugging tools are often powerless to tell the programmer the right solution.

Loops and recursion

It is believed that looping is equivalent to recursion. Indeed, in some cases, a recursive algorithm can be implemented in the syntax of conditional and cyclic constructions.

However, if there is a clear understanding that a particular function should be implemented using a recursive algorithm, any external use of a loop or conditional statements should be abandoned.

implementation of recursive algorithms

The point here is that a recursive solution in the form of a function using itself will be a complete, functionally complete algorithm. This algorithm will require efforts by the programmer in its creation, understanding the dynamics of the algorithm, but it will be the final solution that will not require external control.

Any combination of external conditional and cyclic operators will not allow us to represent a recursive algorithm in the form of a complete complete function.

Consensus of Recursion and OOP

In almost all variants of the development of a recursive algorithm, there is a plan to develop two algorithms. The first algorithm generates a list of future objects (instances), and the second algorithm is a recursive function itself.

The best solution would be to recurse in the form of a single property (method) that actually contains a recursive algorithm, and put all the preparatory work into the constructor of the object.

A recursive algorithm will only be the right solution when it works only by itself, without external control and management. An external algorithm can only give a signal to work. The result of this work should be the expected solution, without external support.

Recursion should always be a complete independent decision.

Intuitive understanding and functional completeness

When object-oriented programming became the de facto standard, it became obvious: for effective coding, one should change one's own thinking. The programmer must move from the syntax and semantics of the language to the dynamics of semantics during the execution of the algorithm.

A characteristic feature of recursion: it can be applied in everything:

  • parsing sites;
  • search operations;
  • analysis of textual information;
  • reading or creating MS Word documents;
  • tag selection or analysis ...

A characteristic feature of OOP: it makes it possible to describe a recursive algorithm at the level of an abstract ancestor, but provide for it to refer to unique descendants, each of which has its own palette of data and properties.

the concept of recursive algorithms

Recursion is ideal because it requires the functional completeness of its algorithm. OOP improves the quality of a recursive algorithm by giving it access to all unique descendants.

Source: https://habr.com/ru/post/F34817/


All Articles