Data Structure and Algorithm (Golang Implementation) (8.1) Basic Knowledge-Preface

Basic knowledge

Learn data structures and algorithms. We need to know some basic knowledge.

1. What is an algorithm

algorithmThe word " algorithm" (English ) is extensive and profound in Chinese, and it means the method of accounting, and it can also mean strategic planning. What does it mean in computer technology?

A computer, as the name suggests, is a machine used for computing. Algorithms in computer science can be described as: the computer receives an input instruction, then performs a process, and finally outputs the result of the calculation.

This input-process processing-output is easy to understand using human behavior patterns. For example, my mother asked Xiaoming to play soy sauce. The command to play soy sauce is input. Xiaoming found that there are 5 shops around the community with soy sauce for sale. Juanjuan supermarket is The closest to home, and Zilong grocery store is the farthest away, but soy sauce is very cheap. In order to save money, Xiao Ming went to the farthest Zilong grocery store to buy soy sauce, then returned home smoothly and gave it to his mother. The process of buying soy sauce is processing, and the soy sauce for mother is output.

Why didn't Xiaoming go to the nearest Juanjuan supermarket and go to the farthest Zilong grocery store? This is the best plan that comes out after thinking in Xiaoming's head. Of course, now you can buy soy sauce through the take-out software, Xiaoming can open the Meituan take-out software, search for the keyword: soy sauce, and then click to filter, the nearest and cheapest from home, and then select the cheapest soy sauce to place an order.

The process of buying soy sauce = the process of ordering Meituan takeaway software.

In the evolution of human beings for thousands of years, they will be able to perform numerical operations and trade off their interests. Then they will make machines, give their own behavior patterns to machines, and liberate themselves. If humans really understand the information transfer process of human brain neurons, they may even create self-conscious machines, but this kind of scene can still only be seen in science fiction movies.

Therefore, this logical process, or behavior pattern, is mapped to an algorithm in the computer.

In a more accurate description: an algorithm is a method that is 有限,确定,有效suitable for being implemented by computer programs and used to solve problems. First, there is a problem, and then there is a way to solve it. This method is called an algorithm.

The algorithm is limited, that is, the steps of the algorithm are limited, and the execution time is limited, and the result can be obtained in a limited time. The algorithm is determined, that is, no matter how many times it is executed, the calculated result is the same. The algorithm is effective, that is, the calculated result is helpful to solve the problem.

However, the definition of the algorithm has been refreshed all the time. Because of the emergence of machine learning, the steps of the machine learning algorithm are infinite and can be calculated all the time based on the massive and large-scale data. And increase the training threshold, the parameters obtained during training exceed the set threshold to stop the calculation immediately, but also meet the above definition.

The algorithm must be completed in a limited time, which is a burden on humans, because the machines made by humans are not strong enough. why? Because even if the steps of the algorithm are limited, the execution time may be particularly long.

Just as in the book From One to Infinity, the three jewel needles under the temple of Benares, the holy place of Hinduism, the Hindu god Fen Tian said, who can move the 64 gold pieces of the first gem needle through the second gem needle To the third root, the burning tower, the temple, and the Brahmin will be reduced to ashes, which is the famous Hanoi algorithm.

The Hanoi tower problem can be described as:

There are three poles (numbering A、B、C), and a gold plate is Aplaced in order from the bottom to the top, from large to small 64(as shown below). The goal of the game: AMove all the gold plates Con the pole to the pole, and keep the original order folded.

Operation rule: Only one plate can be moved at a time, and the three plates always keep the big plate down and the small plate up, and the plate can be placed on A、B、Cany bar during the operation .

We naturally think of an algorithm:

  1. We must first use the Crod to move the plate in Afront N-1of the Brod to the rod, and then Amove the remaining plate of the Crod directly to the rod. This is Aempty.
  2. Then, with the help of the Arod, move Bthe N-1plates of the Crod to the rod, and the task is completed.

Very simple idea, we use programming language to achieve:

package main

import "fmt"

var total = 0

// 汉诺塔
// 一开始A杆上有N个盘子,B和C杆都没有盘子。
func main() {
    n := 4   // 64 个盘子
    a := "a" // 杆子A
    b := "b" // 杆子B
    c := "c" // 杆子C
    tower(n, a, b, c)

    // 当 n=1 时,移动次数为 1
    // 当 n=2 时,移动次数为 3
    // 当 n=3 时,移动次数为 7
    // 当 n=4 时,移动次数为 15
    fmt.Println(total)
}

// 表示将N个盘子,从 a 杆,借助 b 杆移到 c 杆
func tower(n int, a, b, c string) {
    if n == 1 {
        total = total + 1
        fmt.Println(a, "->", c)
        return
    }

    tower(n-1, a, c, b)
    total = total + 1
    fmt.Println(a, "->", c)
    tower(n-1, b, a, c)
}

By induction, we can know the number of mobile Total(N)relationship is Total(N)=2*Total(N-1)+1, each one more dish, add a mobile number will be doubled, we can see by the number of columns mathematically related Total(N)=2^N-1, that is, the number of mobile is an exponential equation: 2的N次方the index is equal to the dish Quantity.

We calculated that we 2^64-1=18446744073709551615can know that a person moves day and night, moving once a second: 18446744073709551615/3600/24/365/100000000=5849It will take 584.9 billion years to complete this matter. At that time, the world may indeed have been destroyed.

In computer science, because all algorithms are human-defined rules, the rules are dead, so don't worry about not learning. When you learn these algorithms, you will feel, wow, everything is so simple.

Second, what is the data structure

Data structure, as the name implies, is the structure that stores the data, and it can also be regarded as the container that stores the data. For example, if you want to find the maximum value of 1000 numbers, first you need to record 1000 numbers on some cards, and then sort the cards.

Most algorithms need to organize data, so data structures are generated. The data structure in the computer is mainly used to realize the basis of various algorithms. Of course, the data structure itself is also a part of the algorithm.

The basic data structures are: linked list, stack and queue, tree and graph.

A linked list is to link and correlate data. A data node points to another data node, like an iron chain in nature. Most data structures are represented by several variants of the linked list.

In each programming language, the array is provided as a basic data type. The array is a continuous memory storage space, and the data at the specified position of the array can be quickly obtained through the subscripts 0, 1, and 2. The linked list can also be implemented with an array, but in general, because the array is continuous, it is easy to cause redundancy when the linked list adds and deletes nodes, and the effect is not good. So the list is implemented in different programming languages such as: C、C++a pointer to achieve, Javait is implemented by the class, and Golangis achieved with reference to the structure.

Stacks and queues are mainly used to store multiple data, but one is first-in, first-out. For example, when pushing down the stack, the data that is first put on the stack will come out last, and for the queues we are familiar with, those who queue first will definitely get service first.

The second is the tree and the graph. A tree has a root node that stores data. There are many child nodes below it, and data is also stored. Analogous to the tree in nature. A map can be compared to a map in nature. Multiple points point to multiple points, and there are one or more edges between the points. These points store data, and the edges can also store data, such as distance.

There are several extensions around these types of data structures, plus some sorting and search logic to form a higher-level advanced data structure.

The data structure is an aid to the implementation of the algorithm, and is to organize the structure of the data more efficiently, so the data structure and the algorithm are actually closely related, and do not need to be too clearly divided. You can equate the data structure with the algorithm.

Third, what is a good data structure and a good algorithm

The reason for learning algorithms is that good algorithms can save resources, but it is difficult to choose the right algorithm. We need to carry out complex mathematical analysis to know what is good. In the computer, we call this mathematical analysis algorithm analysis.

What are good data structures and good algorithms?

  1. 计算机资源是有限Yes, so the data structures and algorithms that consume less computer resources are better.
  2. 人的生命是有限的Yes, the waiting time is tolerant, so the faster the data structure and algorithm that can assist the program to complete the work, the better.

So there is a theory: time and space algorithm complexity theory.

During program execution, either space for time, or time for space, space can be considered as a computer resource such as memory usage, and time is the fourth dimension of human perception, whether it is slow or fast, the two generally cannot have both If you find that you have both, it is to invent a better algorithm.

In the forty or fifty years of the development of computer science, such inventions that save resources and save time are relatively few, such as data compression algorithms. Because of the ultra-efficient lossless data compression algorithm invented, when we watch videos online, neither Distortion, not stuttering, fast and good, this is called an algorithm.

At present, there is a new type of computing method under study, called quantum computing, which can calculate very large amounts of data in a very small space and using very few resources in a short period of time. Let us look forward to the day when mass production can succeed. , Human productivity will be greatly liberated.

4. Summary

In general, programming is considered by many people = data structure + algorithm.

We learn data structures and algorithms to write faster and better code for higher efficiency.

Because we have studied, we do n’t need to design from scratch, and the work efficiency is improved.

Because we know the complexity and applicable scenarios of each data structure and algorithm, and choose the combination freely, the code we write becomes faster and takes less resources.

Therefore, we must study and understand common data structures and algorithms.

Welcome to the remaining chapters.

Series article entry

I am the star Chen, Welcome I have personally written data structures and algorithms (Golang achieve) , starting in the article to read more friendly GitBook .

Published 12 original articles · praised 0 · visits 91

Guess you like

Origin blog.csdn.net/m0_46803965/article/details/105595061