Take you through the art of algorithms

Keywords: Programming less PHP Big Data

What is an algorithm?
Isn't the equation unfamiliar?The correct unknown value is obtained by solving the equation.We can simply interpret solving equations as algorithms.Of course, the algorithm is more than that. Don't worry, I'll talk to you.
Let's start with two pieces of code:

Both pieces of code can be called algorithms because they solve the problem of adding two numbers together and adding one to n, respectively.Algorithms don't have to be very complex, as small as one line of code, as many as tens of thousands of lines of code. An algorithm is one that can solve a specific problem.

How to evaluate the algorithm

Using different algorithms to solve the same problem can be very efficient

Two existing algorithms for Fibonacci number

(Fibonacci sequence: 1 1 12 3 5 8...)

public static int fib1(int n) {
    if (n <= 1) return n;
    return fib1(n - 1) + fib1(n - 2);
public static int fib2(int n) {
    if (n <= 1) return n;

    int first = 0;
    int second = 1;
    for (int i = 0; i < n - 1; i++) {
        int sum = first + second;
        first = second;
        second = sum;
    return second;

Which of these two algorithms is better?

If you are evaluating performance efficiency alone, you might think of a scenario like this

Comparing execution processing times of different algorithms for the same set of inputs

This scheme is also called post-mortem statistics.

Our approach is:

public static void main(String[] args) {
    int n = 45;//Find the 45th Fibonacci Number

    TimeTool.check("fib1", new Task() {
        public void execute() {
    });//5.815 seconds

    TimeTool.check("fib2", new Task() {
        public void execute() {
    });//0.0 seconds

The above scheme has obvious drawbacks

Execution time depends heavily on hardware and various uncertain environmental factors at runtime

Corresponding calculation code must be written

The selection of test data is more difficult to ensure impartiality (the first algorithm may take less time at n=100 and the second algorithm may take less time at n=200).

Generally, the algorithm is evaluated from the following dimensions

Correctness, readability, robustness (responsiveness and handling of unreasonable input)

time complexity: Estimates the number of executions of program instructions (execution time)

Spatial complexity: Estimate the required storage space

Let's evaluate the algorithm for calculating 1+2+...+n using this scheme

Obviously the second algorithm is better.Is it because the second method has shorter code?The example of the Fibonacci sequence tells us that shorter codes are not better.In this example, the second algorithm only needs three steps to solve the problem, while the first one needs to loop n times.First, they all satisfy the conditions of correctness, readability and robustness. Then, in terms of time complexity, assuming a certain execution time of one step operation, we can compare the two algorithms by examining how many instructions they need to execute. Then, considering the spatial complexity, the fewer variables needed, the smaller storage space opened up, the better the algorithm.

#Large O notation

Complexity is generally described in terms of large O, which represents the complexity corresponding to data size n

Method steps:

(1) Estimate time/space complexity (mainly time complexity)

(2.1) Ignore constants, coefficients, lower orders

         $9$>> O(1) 

         $2n+6$ >> O(n)              

         $n^2+2n+6$ >> O($n^2$) 

         $4n^3+3n^2+22n+100$ >> O($n^3$) 

(2.2) Omit the base number for logarithmic order in general

         $log_2n=log_29+log_9n$(logarithms of any base number can be converted to each other by multiplying a constant)

         So $log_2n$, $log_9n$are collectively referred to as $logn$

Note: The Large O notation is only a rough analysis model and an estimate that can help us understand the efficiency of an algorithm in a short time

Calculate the time complexity of the following sections of code

public static void test1(int n) {
    //1 (make a judgment)
    if (n > 10) { 
        System.out.println("n > 10");
    } else if (n > 5) { // 2
        System.out.println("n > 5");
    } else {
        System.out.println("n <= 5"); 
    // 1 (define once i) + 4(i adds up four times) + 4 (judge I < 4 times) + 4 (loop body executes a statement four times) =9
    for (int i = 0; i < 4; i++) {
    // Large O Representation Time Complexity O(1)
public static void test2(int n) {
    // 1 (define once i) + 3n (i accumulate n times + judge I < n times + execute a statement i n loop n times) = 1+3n
    for (int i = 0; i < n; i++) {
    // Large O Representation Time Complexity O(n)
public static void test3(int n) {
    // 1 (define once i) + 2n (i accumulate n times + judge I < n times) + n (outer loop statement executes n times) * (define once j) + 3N (j accumulate n times + judge J < n times + inner loop statement executes n times) = 3n^2 + 3n + 1
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
    // Large O Representation Time Complexity O(n^2)
public static void test4(int n) {
    // 8 = 2^3
    // 16 = 2^4

    // 3 = log2(8)
    // 4 = log2(16)

    // Number of executions = log2(n)
    while ((n = n / 2) > 0) {
    // Large O Representation Time Complexity O(logn)
public static void test5(int n) {
    // log5(n)
    while ((n = n / 5) > 0) {
    // Large O Representation Time Complexity O(logn)
public static void test7(int n) {
    // 1 (Define once i) + 2*log2(n)(i*2 Operational Number) + log2(n) (Outer Loop Execution Number) * (1 + 3n) (Inner Loop Execution Number)
    for (int i = 1; i < n; i = i * 2) {
        // 1 + 3n
        for (int j = 0; j < n; j++) {
    // 1 + 3*log2(n) + 2 * nlog2(n)
    // Large O Representation Time Complexity O(nlogn)


Comparing complexity with function generation tools


Because the space is limited, there are no more explanations here.In a word, in the big data era, the use and development of algorithms are getting more and more attention.Algorithms are coming into people's lives too, and you may not have noticed that the weather forecasting app s you use, the financial software you use, and so on, are all implemented through algorithms.So, come on coder!

If you want to improve yourself and learn more algorithms and advanced programming language skills, here are free related learning materials. Welcome to Gatwise: 19950277730 for more tips on technology improvement.There are not only like-minded little partners here, but also countless free programming skills, learning videos and materials, plus WeChat to explore learning technology!!

Posted by koddos on Sat, 09 Nov 2019 10:07:20 -0800