Algorithmization, algorithms, languages ​​and programs. Algorithmization and programming Examples of algorithms programming

Articles like “do programmers need algorithms” often appear, and they all have approximately the same template. The author of the article usually writes: “I have been writing websites/scripts in 1C for N years, and have never used algorithms or data structures. They immediately give examples of red-black trees or some other exotic structures, which in the area in which the author works are not often seen, if at all. Such articles boil down to the fact that in a particular area programmers do not use complex structures data and do not solve NP problems.

The very formulation of such a question is fundamentally incorrect. The number of specialties in the industry is constantly growing, and a person who writes websites on .net will do completely different things than a person who writes drivers for sensors on ARM architecture under an exotic OS. Let's first define what an algorithm is. Informally, Cormen defines an algorithm as a well-defined procedure that takes one or more values ​​as input, and returns one or more values ​​as a result. Formally, the algorithm is defined in different models computation: operations that can be performed on a Turing machine or using lambda calculus. So virtually any code that does something is an algorithm. It turns out that the question “does a programmer need algorithms” can be translated as “does a programmer need to be able to write code?” The correct question should be something like: “does a programmer in industry X need to know advanced algorithms and details of computational theory.”

If you look at all these articles, you will notice that the people who write them are actually offended by universities because they were forced to learn a lot of complex material - in the form of algorithmic analysis, complex algorithms and data structures - which did not seem to be useful to them . In fact, the authors of the articles are offended by universities because they were unable to predict the future field of work of the authors and give them only the minimum required set of skills. Indeed, in order to write simple websites and scripts, you do not need special knowledge of algorithms and data structures. Or is it still necessary?

Let's think about what a programmer needs to study at university in order to acquire the necessary skills for a successful career. Libraries? Frameworks? They become outdated, their interfaces change, they are all written most often in one language, which students may never use in the industry. Should we teach everyone how to write websites? Or teach everyone how to write an OS? Education should reach the widest possible audience and provide the widest possible range of skills. A programmer must first of all be able to analyze and solve problems - this is the main skill that computer science graduates should acquire. Writing code is easy necessary tool, which is used to solve problems. Who knows what skills you will need in the future? Thus, learning theory is the most optimal from an educational point of view. The acquired skills can be applied in any field, and learning a library or framework with a good knowledge base will not be difficult. The paradox is that people who ask questions about the need for algorithms usually have some knowledge in this area. I do not remember a single person who did not have knowledge in the field of computational theory and proudly shouted about it, claiming that he did not need it.

So, you are an abstract programmer in a vacuum, you have been working for more than ten years putting together websites and solving simple, similar problems for clients/company. You feel good and comfortable in your niche, and only excruciatingly pain for wasted time in a class on computational theory and algorithmic analysis that gave you nothing. In the morning, while lighting a cigarette over a cup of coffee, in the depths of philosophical reflections on the frailty of existence, you wonder: why do programmers who do not solve complex problems need to know algorithms and the basics of analysis. The short answer is to be skilled and effectively use the tools available, including the language in which you write. The theory of algorithms and analysis teaches not only exotic algorithms and data structures in the form of AVLs and red-black trees. It also gives ideas on how to effectively organize data, how to write code with maximum performance, where a bottleneck is possible in the system and how to deal with it. You are introduced to ready-made solutions so that you don’t write bicycles and don’t run to Google every time you need to do something non-trivial.

Knowledge of the theory of analysis and algorithms is actually used by all programmers every day, we’re just so used to these things that we don’t even think about it. Whatever problem you solve - be it a simple website with data fetching from a database, or a bash script on a server, you will use some kind of data structures. At least a primitive array, and most likely something more complex. Languages ​​give us many different structures, many of which are used interchangeably. Often we have several variations of the same abstract type with different implementations. For example, C++ has vector and list data structures. How are they different, and what would be the advantages and disadvantages of using one or the other? How is map implemented in C++, and how does it differ from multimap? How is list implemented in Python - via an array or a linked list and what is the best way to work with it? Why is it not advisable to use an ArrayList in C# and instead use a List? How is SortedDictionary implemented and how will it affect program execution if used instead of Dictionary? How does continuation work, when should it be used, and are there any side effects when using it? When was the last time you used curried functions, which are found in almost every language? If you think that map in C++ is implemented as a hash table, you are wrong. It is implemented on red-black trees, and the hash table is implemented by unordered_map. Separately worth mentioning dynamic programming. Understanding what it is, how recursive functions can be rewritten optimally, and what memoization is will often help you avoid shooting yourself in the foot. Thus, just to fully and effectively use the language in which you write, you already need to have at least a superficial knowledge of data structures, what they are, and how they can affect the execution of your program.

What about libraries? After all, they solve so many problems! To use libraries efficiently, you also need to understand them. First, functions in libraries may have side effects or behavior that you wouldn't know without understanding the algorithms. Having received a bug in this case, you can try long and hard to catch it and decide when it could have been avoided. Secondly, various tools and libraries often need to be “customized” - told what algorithms, data structures and technologies to use internally. Without basic knowledge, you will have to either go read mana or choose at random. Thirdly, there are many problems that cannot be solved by simply calling the API of a library or framework. What will you do in this case? Spend hours searching possible solutions and ask a friend for help? Fourthly, many problems can be solved very simply with a few lines of code or built-in language tools. If you pull out a library to solve every problem, then your programs will be giant monsters, occupying hundreds of megabytes or more on disk, eating up all the memory on the server, and at the same time having rather meager functionality. In addition, the presence of a bunch of included libraries entails compatibility problems, and the program may crash randomly due to the strange behavior of several libraries in one project. Thoughtless use of libraries can lead to quite disastrous consequences, and developers who only know how to use libraries but are unable to solve even a simple problem on their own will never be valued because their solutions will not be competitive.

One programmer with more than ten years of experience worked with me. One day we needed a function that the library we used did not support at that time: a primitive text-wrap in one of the visual components. This “programmer” looked at what standard means this cannot be done, and immediately stated that the implementation of such a function is impossible. The problem was solved by a third-year intern with an analytical brain, who wrote a simple algorithm in two hours and implemented it into the required component. I inherited another project in the form of a website on .net. The main page consisted of several small graphs and took almost 10 seconds to load. It turned out that the person who originally did this project piled up a bunch of terrible designs from triple nested loops, which took a long and sad time to take data from the database and then tie it to graphs. After some refactoring, the page loaded almost instantly.

Can a programmer do without knowledge of algorithms and analysis theory? Maybe there are a lot of such “programmers”. It would be a stretch to call them programmers. A lot of programmers come to me for interviews, with ten to fifteen years of experience, and not really understanding what they do and why. They have their own niche, they go from company to company, without staying in them for more than a year. As a rule, they have a small set of tasks that they can solve, and if you take a step to the side, then the person is lost and needs to teach himself new skills. Such people are invited to the project, and they get rid of them as quickly as possible, because they waste a lot of time reinventing wheels and reading mana to learn what they should have already known from university. As a rule, they do not have any particular career and unstable income.

In the end, why do you need to know algorithms and analysis theory if you can do the work without this knowledge? To be a qualified specialist in your profession, have career growth and respect from colleagues. To effectively solve problems and not reinvent the wheel. In order not to write monsters with a huge number of third-party libraries, which take up hundreds of megabytes on the disk, eat up a lot of memory on the server and regularly crash for a random reason depending on the phase of the moon. To use the language you write effectively and to the fullest extent possible. To make informed and meaningful decisions about the choice of library and technology to solve a problem. If your job is to write SQL query and typing a command into the console, then I want to disappoint you: you are not a programmer, you are a user, you really don’t need algorithms and the like, and you wasted your time at the university because for such work it is enough to complete courses or read a couple of introductory books yourself .

Annotation: Subject of the science of programming. Example and properties of the algorithm. Programming paradigms (directive, object-oriented and functional logic programming).

This chapter, which begins the course, serves two main purposes:

  • prepare the necessary theoretical basis for subsequent mastery various methods information processing, small-scale programming skills and building correct, effective programs;
  • give the minimum knowledge about the Java language necessary for practical programming and provide samples of small typical programs.

In the process of getting acquainted with the theoretical material of the chapter, you may feel that it is disconnected from the needs of practice - solving specific problems in the Java language. On the other hand, it is the solution of programming problems that should lead to a conscious understanding of the fact that writing a correct and effective program is not at all as simple as it seems at first glance.

Knowledge of the necessary theoretical foundations will allow in the second chapter to move on to the study of methods for constructing programs and proving their correctness - a theory that will be used for practical writing of programs in parallel with familiarization with it. Thus, two seemingly completely unrelated streams of studying the material - theoretical and practical - will merge into one in the next chapter. For now, the reader can only believe that knowledge Total The material of the first chapter is a necessary condition for a successful transition to the study of the next one.

And the last remark is purely technological. At the first stage of learning the Java language, it is useful to distract from the fact that it is object-oriented and focus on the substantive problems of correct implementation of the algorithm. However, this is not so easy to do - writing even the most the simplest program it is impossible without understanding the basic concepts of OOP. To partially solve this problem, a class created specifically for these purposes is used Xterm, shielding the novice programmer from the complexities of the real world of the Java language.

Subject of programming science

For a long time, people have had to create descriptions of the sequences of actions required to achieve some goal. Such descriptions may be designed to be performed by humans or automatic devices. Texts written for people tend to have a certain degree of vagueness and informality. An example would be a phrase from a culinary recipe about a pinch salt. Only a very experienced person is able to properly salt a dish in accordance with such a recommendation.

This example explains why sequence descriptions intended to automatic device, must be completely unambiguous and specified using some formal notation system. Very often, the creation of such descriptions is associated with significant technical and fundamental difficulties. This problem has become extremely relevant due to the widespread spread of electronic computers (computers), often used as .

A description of a sequence of actions sufficiently specific that it can be carried out by some automatic device is called algorithm. Usually this sequence is written (encoded) using some formal notation. In this case, the formal system designed to write algorithms is called algorithmic language, the text of the algorithm itself - program, and the process of its creation is programming.

Computer science is engaged in researching the properties of algorithms and developing methods for constructing programs. In terms of its position and the methods used, it is a field of applied mathematics. All attempts to approach programming as a technical discipline, and to create programs as an industrial production, have invariably failed.

Note that the “definition” of the algorithm given above is quite vague and, in fact, is not a definition. In mathematics, there are several very clear definitions of an algorithm that are equivalent to each other, and most of them are not too difficult to understand. All of them, however, require good knowledge certain areas mathematics and therefore at the beginning we will not be distracted by the (very important and interesting) details necessary for a rigorous presentation of the concept of an algorithm. Instead, we'll look at an example algorithm and then list the basic properties that any algorithm should have.

The approach when some not fully clearly defined concept is actively used is very typical in science. For example, exact definitions of natural and real numbers are not considered not only in high school, but even in most universities. Moreover, they say that the centipede even forgot how to walk when he thought about the order in which he rearranged his legs.

Example and properties of the algorithm

Let us need to solve the problem of finding the smallest prime divisor of a natural number greater than one. Let us remind you that simple is a number that has no divisors other than one and itself, and one is not included in the set of prime numbers. This is how we will write down the formulations of problems and their solutions in this book:

Problem 1.1. Come up with an algorithm that introduces a natural number greater than one and finds the smallest prime divisor of this number.

Algorithm for solving the problem.

Algorithm P:

P1: Set the integer equal to two and go to step P2.

P2: If divisible by , then terminate the algorithm, producing ; otherwise go to step P3.

P3: Increase the value by one and go to step P2.

In order to understand this algorithm, you need to act as a computer (or rather, even universal command executor), manually performing the sequence of actions specified in it for some small values. We will record the values ​​of the quantity after each step of the algorithm.

k = 3 k = 4 k = 2
P1: i = 2 P1: i = 2 P1: i = 2
P2: i = 2 P2: i = 2 P2: i = 2
P3: i = 3
P2: i = 3

Such a study gives reason to believe that after the completion of the algorithm, the variable will indeed contain the smallest prime divisor of the original number. In this case, it is not difficult to prove and is completely rigorous. Be sure to do this.

Basic properties of any algorithm are finiteness, certainty, input (input), output (output) and efficiency. Let's consider them sequentially in more detail.

Limb. The algorithm must always end after completing a finite number of steps. Algorithm P satisfies this condition, since the value is initially less than , its value increases by one for each successive execution of step P2, and therefore the execution of the algorithm will be terminated at step P2 if , if is a prime number, or earlier if .

Certainty. The actions to be performed at each step must be defined strictly and unambiguously in every possible case. In this example, a fairly specific, although not entirely formal, notation system is used. More often, algorithms are written using more formal algorithmic languages, also called programming languages, in which each statement has a precise meaning.

Currently, there are several thousand programming languages, dozens of them are actively used. Such a large number of languages ​​is due to the diversity of application areas, differences in the equipment for which programs are written, and in the level of training of the people writing them, as well as the existence of several teachings on how to write programs (the so-called programming paradigms).

Input. The algorithm always has a certain (sometimes equal to zero) amount of input data, that is, values ​​​​transmitted to it before starting work. In algorithm P, for example, one input value is an integer greater than one. An example of an algorithm that has an empty set of inputs is an algorithm that calculates the 1000th prime number.

Output. An algorithm must always have one or more output values. In the case of algorithm P, this value is the number . Algorithms that have no output are useless in practice, and we will not study them.

Efficiency. The algorithm is required to be efficient. This means that all the operations that need to be performed in the algorithm must be simple enough that in principle they can be performed accurately and in a finite time using pencil and paper. In algorithm P, only the following operations are performed: two integers are compared, one positive number is divided by another, a variable is assigned the value of the integer two, its value is increased by one.

All of these operations are efficient in the above sense because integers can be written down on paper in a finite way and there is at least one way to divide and add two integers. But the same operations would not be effective if the values ​​of the quantities appearing in the algorithm were arbitrary real numbers expressed in infinite decimal fractions, since such quantities cannot even be written down on paper in a finite time.

From the above it follows that on a computer almost impossible to work with real numbers, which, apparently, may seem implausible to you. This is actually true. Moreover, even real integers are not used very often on a computer. Usually, instead of sets of integers and real numbers, you have to work with their substitutes


Knuth-Morris-Pratt algorithm

The Knuth-Morris-Pratt (KMP) algorithm receives the word X=xx... x[n] as input and scans it from left to right letter by letter, filling in the array of natural numbers l... l[n], where l[ i]=word length l(x...х[i]) (function l is defined in the previous paragraph). In words: l[i] is the length of the longest beginning of the word x...x[i], which is also its end.

What does all this have to do with subword searching?

In other words, how do you use the KMP algorithm to determine whether word A is a subword of word B?

Solution. Let's apply the KMP algorithm to the word A#B, where # is a special letter that is not found in either A or B. The word A is a subword of the word B if and only if among the numbers in the array l there is a number equal to the length of the word A.

Describe the algorithm for filling the table l...l[n].

Solution. Let's assume that the first i values ​​l...l[i] have already been found. We read the next letter of the word (i.e. x) and must calculate l.

In other words, we are interested in the beginning Z of the word x...x . The word Z" is the beginning and end of the word x...x[i]. However, not any word that is the beginning and end of the word x...x[i] is suitable - it must be followed by the letter x.

We get the following recipe for finding the word Z. Consider all the beginnings of the word x...x[i], which are also its ends. From them we will select the suitable ones - those followed by the letter x. From those that are suitable, we will choose the longest one. By adding x to its end, we get the desired word Z. Now it’s time to use the preparations we have made and remember that all words that are both the beginning and the end of a given word can be obtained by repeatedly applying the function l from the previous section to it.

Here's what happens:

(table l..l[i] is filled out correctly)

while i<>n do begin

(len is the length of the beginning of the word x..x[i], which is

its end; increasingly longer beginnings turned out to be

unsuitable)

while(x<>x) and (len>0) do begin

if x=x do begin

(x..x is the longest suitable beginning)

(no suitable ones)

Prove that the number of actions in the algorithm just given does not exceed Cn for some constant C.

Solution. This is not entirely obvious: processing each successive letter may require many iterations in the inner loop. However, each such iteration reduces len by at least 1, in which case l will be noticeably less than l[i]. On the other hand, when i increases by one, the value of l[i] can increase by no more than 1, so it cannot decrease often or greatly - otherwise the decrease will not be compensated by the increase.

More precisely, we can write the inequality

l

(number of iterations at the i-th step)<= l[i]-l+1

It remains to add these inequalities over all i and obtain an upper bound for the total number of iterations.

We will use this algorithm to find out whether a word X of length n is a subword of a word Y of length m. (How to do this using a special # separator is described above.) In this case, the number of actions will be no more than C(n+m), and the memory used will also be used. Figure out how to use a memory of no more than Cn (which can be significantly less if the searched pattern is short and the word in which it is searched is long).

Solution. We apply the KMP algorithm to the word A#B. In this case: we calculate the values ​​l,...,l [n] for a word X of length n and remember these values. Next, we remember only the value of l[i] for the current i - besides it and besides the table

l...l[n], we don’t need anything for calculations.

In practice, words X and Y may not be in a row, so it is convenient to view word X and then word Y as separate loops. This also eliminates the hassle of using a separator.

Write an appropriate algorithm (checking whether the word X=x...x[n] is a subword of the word Y=y...y[m]

Solution. First we calculate the table l...l[n] as before. Then we write the following program:

(len - length of the maximum download of word X, at the same time

which is the end of the word y..j[j])

while (len<>n) and (j<>m) do begin

while(x<>y) and (len>0) do begin

(the beginning is not suitable, apply the l function to it)

(found a suitable one or were convinced of its absence)

if x=y do begin

(x..x is the longest suitable start)

(no suitable ones)

(if len=n, the word X was encountered; otherwise we reached the end

word Y without ever meeting X)

Boyer-Moore algorithm

This algorithm does what at first glance seems impossible: in a typical situation, it reads only a small part of all the letters of the word in which a given pattern is searched. How can this be? The idea is simple. Let, for example, we are looking for the pattern abcd. Let's look at the fourth letter of the word: if, for example, it is the letter e, then there is no need to read the first three letters. (In fact, the pattern doesn't have an e, so it can't begin until the fifth letter.)

We will present the simplest version of this algorithm, which does not guarantee fast operation in all cases. Let x...x[n] be the pattern to look for. For each character s, we find its rightmost occurrence in the word X, that is, the largest k for which x[k]=s. We will store this information in the pos[s] array; if the symbol s does not occur at all, then it will be convenient for us to set pos[s]=0 (we will see why later).

How to fill the pos array?

set all pos[s] equal to 0

for i:=1 to n do begin

During the search process, we will store in the last variable the number of the letter in the word opposite which the last letter of the sample appears. At first last=n (sample length), then last gradually increases.

(all previous positions of the sample have already been checked)

while last<= m do begin {слово не кончилось}

if x[m]<>y then begin (last letters are different)

last:=last+(n-pos]);

(n - pos] is the minimum sample shift,

at which opposite y there will be the same

letter in the sample. If there is no such letter at all,

then we shift it along the entire length of the sample)

if the current situation is suitable, i.e. If

x[i]..х[n]=y..y,

then report a match;

Experts recommend checking for matches from right to left, i.e. starting with the last letter of the sample (in which there is obviously a match). You can also save a little by doing the subtraction in advance and storing not pos[s], but n-pos[s],

those. the number of letters in the pattern to the right of the last occurrence of the letter. Various modifications of this algorithm are possible. For example, you can have the line

replaced by

last:=last+(n-u),

where u is the coordinate of the second occurrence of the letter x[n] from the right in the pattern.

What is the easiest way to take this into account in the program?

Solution. When constructing the table pos write

write

last:=last+n-pos];

The presented simplified version of the Boyer-Moore algorithm in some cases requires significantly more n actions (the number of actions is of the order of mn), losing to the Knuth-Morris-Pratt algorithm.

An example of a situation in which the pattern is not included in the word, but the algorithm requires about mn actions to establish this.

Solution. Let the sample look like baaa... aa, and the word itself consists only of the letters a. Then at each step the discrepancy is clarified only at the last moment.

The real (not simplified) Boyer-Moore algorithm guarantees that the number of actions does not exceed C(m+n) in the worst case. It uses ideas close to those of the Knuth-Morris-Pratt algorithm. Let's imagine that we compared the sample with the input word, going from right to left. In this case, some piece of Z (which is the end of the sample) coincided, and then a difference was discovered: the Z in the sample is preceded by something different from the one in the input word. What can be said at this moment about the input word? It contains a fragment equal to Z, and the letter in front of it is not the same as in the sample. This information can allow a pattern to be moved a few positions to the right without the risk of missing its occurrence. These shifts should be calculated in advance for each Z end of our sample. As experts say, all this (calculating the shift table and using it) can be done in C(m+ n) actions.

Rabin's algorithm

This algorithm is based on a simple idea. Let's imagine that in a word of length m we are looking for a pattern of length n. Let's cut out a window of size n and move it along the input word. We are interested in whether the word in the box matches the given pattern. It takes a long time to compare letters. Instead, we fix some function defined on words of length n. If the values ​​of this function on the word in the box and on the sample are different, then there is no coincidence. Only if the values ​​are the same should you check for a letter-by-letter match.

What is the gain with this approach? It would seem nothing - after all, in order to calculate the value of a function on a word in a window, you still need to read all the letters of this word. So it’s better to immediately compare them with the sample. Nevertheless, winning is possible, and here’s why. When you move the window, the word does not change completely, but only a letter is added at the end and removed at the beginning. It would be nice if this data could be used to calculate how the function changes.

Give an example of a function convenient for calculation.

Solution. Let's replace all the letters in the word and pattern with their numbers, which are integers. Then a convenient function is the sum of the digits. (When you move the window, you need to add a new number and subtract the missing one.)

For every function there are words to which it is poorly applicable. But another function in this case may work well. An idea arises: you need to store a lot of functions and select a random one from them at the beginning of the algorithm. (Then the enemy who wants to mess with our algorithm will not know which function to fight.)

Give an example of a family of convenient functions.

Solution. Let's choose some number p (preferably prime, see below) and some residue x modulo p. We will consider each word of length n as a sequence of integers (replacing letters with codes). We will consider these numbers as coefficients of a polynomial of degree n-1 and calculate the value of this polynomial mod p at point x. This will be one of the functions of the family (for each pair p and x, therefore, its own function is obtained). Shifting the window by 1 corresponds to subtracting the leading term (xn-1 should be calculated in advance), multiplying by x and adding the dummy term.

The next consideration suggests that coincidences are not very likely. Let the number p be fixed and also prime, and X and Y be two different words of length n. Then they correspond to different polynomials (we assume that the codes of all letters are different - this is possible if p is greater than the number of letters of the alphabet). The coincidence of function values ​​means that at point x these two different polynomials coincide, that is, their difference becomes 0. The difference is a polynomial of degree n-1 and has no more than n-1 roots. Thus, if u is much less than p, then random x has little chance of hitting the wrong point.

Similar documents

    Theoretical information. Basic concepts. String, its length, substring. The concept of algorithm complexity. Algorithms based on the sequential search method. Algorithms of Rabin, Knuth - Morris - Pratt, Boyer - Moore.

    course work, added 06/13/2007

    Organization of the ability to view text files and search for the necessary words in the text. Editing text (font, size). Algorithm for searching a substring in a string (Knuth-Morris-Pratt method). Loading text from a file (with extension .txt).

    course work, added 05/29/2013

    Search in arrays and lists, key and arbitrary data. Linear (sequential) search. Binary search in an ordered array. Rabin-Karp algorithm, a simple and improved hash function. Boyer-Moore algorithm with shift by stop characters and suffixes.

    presentation, added 10/19/2014

    Study of the concept of an algorithm, features of linear and branching algorithms. Properties of the algorithm: understandability, accuracy, discreteness, mass production and effectiveness. Drawing up a program to calculate the value of a function and plotting its graph.

    test, added 03/25/2013

    Study of the definition, description and call of functions, pointers and references to them. Writing a function to multiply an arbitrary column of a two-dimensional array by const. Multiplying 2 array columns by constants. Drawing up a block diagram of the algorithm and program text.

    laboratory work, added 01/09/2012

    Basic properties of the algorithm. The formal and informal executor of the algorithm, the system of its commands. Methods for writing an algorithm. Verbal description, line-by-line recording, supporting summary. Characteristics of an algorithmic language. Execution of the algorithm by a computer.

    presentation, added 04/04/2014

    Theoretical and practical aspects of solving applied problems using functions and procedures of structured (modular) programming. Features of the development of an algorithm scheme and a program for calculating an array z in the Turbo Pascal 7.0 language, their description.

    course work, added 12/11/2009

    Characteristics of the implementation features of array search using linear, binary, Fibonace tree and extrapolar methods using the Turbo Pascal language program. Adaptation of the Rabin-Karp and Knuth-Morris-Pratt algorithm for finding a row in a row.

    course work, added 09/16/2010

    Description of the operating principle of a genetic algorithm, testing its operation for functions according to the option based on a ready-made program. Basic parameters of the genetic algorithm, its structure and content. Methods for implementing the algorithm and its components.

    laboratory work, added 12/03/2014

    Development in assembly language of a control algorithm using a cyclic CRC code for a data array stored in a certain memory area. Saving code for subsequent periodic checking of the data array. Data corruption message. Description of the algorithm.

2.4.1. The concept of basic algorithms

2.4.2. Linear structure algorithms

2.4.3. Basic algorithms for branching structures and examples of their programming

2.4.4. Basic algorithms for regular cyclic structures and examples of their programming

2.4.5. Basic algorithms for iterative cyclic structures and examples of their programming

2.4.6. Basic algorithms for processing one-dimensional arrays

2.4.7. Basic algorithms for processing two-dimensional arrays

2.4.8. Test questions on the topic “Basic algorithms and examples of their implementation”

2.4.9. Test tasks on the topic “Basic algorithms and examples of their implementation”

2.4.1. The concept of basic algorithms

Basic data processing algorithms are the result of decades of research and development. But they continue to play an important role in the expanding use of computing processes.

The basic imperative programming algorithms include:

    The simplest algorithms implementing basic algorithmic structures.

    Algorithms working with data structures. They define the basic principles and methodology used to implement, analyze, and compare algorithms. Provides insight into data presentation methods. Such structures include linked lists and strings, trees, and abstract data types such as stacks and queues.

    Algorithms sorting, designed to organize arrays and files, are of particular importance. Related to sorting algorithms are priority queues, selection problems, and merging problems.

    Algorithms search, designed to find specific elements in large collections of elements. These include basic and advanced search methods using trees and digital key transformations, including digital search trees, balanced trees, hashing, and methods that are suitable for working with very large files.

    Graph Algorithms useful in solving a number of complex and important problems. A general graph search strategy is developed and applied to fundamental connectivity problems, including shortest path, minimum spanning tree, network flow, and matching problems. The unified approach to these algorithms shows that they are based on the same procedure, and that this procedure is based on the underlying abstract priority queue data type.

    Algorithms string processing include a number of methods for processing (long) character sequences. Searching a string leads to pattern matching, which in turn leads to parsing. File compression technologies can also be attributed to this class of tasks.

2.4.2. Linear structure algorithms

Example 2.4.2-1.

where x = -1.4; y = 0.8; variables k and k are of integer type, the remaining variables are of real type; [n] is the integer part of the number n.

The diagram of the algorithm and programs in the languages ​​QBasic, Pascal, C++ are presented in Fig. 2.4.2-1.

Please note that the integer variable k received a rounded value n, and the integer variable m- truncated using a function FIX() to the whole part of the value n.

Example 2.4.2-2. Calculate and display the following values:

where x = 2.9512; y = 0.098633; variables i and j are of integer type; the remaining variables are of real type.

The algorithm diagram and program codes are presented in Fig. 3.2.1-2.

Rice. 2.4.2-2.

The results of executing the program with the above values ​​of the initial data have the following form:

Example 2.4.2-3. Calculate and display the value of the first escape velocity.

Let's formalize it. The minimum speed at which a spacecraft in the Earth's gravitational field can become an artificial satellite is equal to

where is the gravitational constant; M – mass of the Earth;
– distance from the center of the Earth to the spacecraft.

The algorithm diagram and program codes are presented in Fig. 3.2.1-3.

Rice. 2.4.2-3.

The results of executing the program with the above values ​​of the initial data have the following form.