Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Fundamentals of Algorithms and Analysis Methods

Fundamentals of Algorithms and Analysis Methods

In the world of computer science,Algorithm is the computer's recipe; it is a clear, finite, executable sequence of instructions used to solve a specific problem or complete a specific computational task. Whether it is navigation software on your phone planning the shortest path, or a search engine finding the most relevant web pages from massive data in milliseconds, all rely on carefully designed algorithms.

Understanding the fundamentals and analysis methods of algorithms is a key step for every programmer from being a code implementer to a problem solver.

This article will systematically introduce you to the core concepts of algorithms and teach you how to scientifically evaluate the merits of an algorithm.


Core characteristics of algorithms

A qualified algorithm must have the following five basic characteristics, which we can understand using the analogy of cooking:

  1. Finiteness: An algorithm must terminate after a finite number of steps. Just as a recipe cannot ask you to stir infinitely until the end of the universe, it must give a clear stopping condition.
  2. Definiteness: Each step of the algorithm must have a precise definition with no ambiguity. For example, "add a little salt" is uncertain, while "add 5 grams of salt" is definite.
  3. Feasibility: Every operation in the algorithm must be basic and executable. You cannot write "use telepathy to beat the eggs" in a recipe.
  4. Input: An algorithm has zero or more inputs. These inputs are the objects the algorithm processes, like the ingredients a recipe needs.
  5. Output: An algorithm has one or more outputs. Outputs are quantities with a specific relationship to the inputs, the result of the algorithm's execution, like the final prepared dish.

How to describe an algorithm?

We can describe an algorithm in many ways; the three most common are:

1. Natural language description

Describe the algorithm's steps in human language (such as Chinese or English). The advantage is ease of understanding, but the disadvantage is lack of precision and prone to ambiguity.

Example: Find the maximum of three numbers.

  1. Compare the first and second numbers, remember the larger one.
  2. Compare the number remembered in the previous step with the third number.
  3. Output the larger number as the maximum.
  4. 2. Flowchart

    Use graphical symbols to represent the control flow of an algorithm. It intuitively shows the logical relationships between steps.

    Flowchart explanation: This diagram clearly shows the decision process of the algorithm for finding the maximum of three numbers. Diamonds represent conditional judgments, rectangles represent processing steps, and arrows indicate the direction of program execution.

    3. Pseudocode

    A description method between natural language and programming languages. It uses programming-language-like structures (such as if, for, while), but ignores specific syntax details, focusing on logical expression.

    算法:FindMax
    输入:三个数字 a, b, c
    输出:最大值 max
    
    1.  if a > b then
    2.      max = a
    3.  else
    4.      max = b
    5.  end if
    6.  if c > max then
    7.      max = c
    8.  end if
    9.  输出 max
    

    4. Programming language implementation

    Ultimately, an algorithm needs to be translated into code in some programming language (such as Python, Java, C++) to run on a computer.

    Example

    Python implementation: find the maximum of three numbers

    def

    find_max

    (

    a

    ,

    b

    ,

    c

    )

    :

       

    First compare a and b, assign the larger value to max_value

       

    if

    a

    b:

            max_value

    =

    a

       

    else

    :

            max_value

    =

    b

       

    Then compare max_value with c

       

    if

    c

    max_value:

            max_value

    =

    c

       

    return

    max_value

    Test code

    print

    (

    find_max

    (

    5

    ,

    9

    ,

    3

    )

    )

     

    Output: 9

    print

    (

    find_max

    (

    1

    ,

    0

    ,

    1

    )

    )

    Output: 1

    Output result:

    9
    1
    

    Algorithm analysis: how to evaluate the quality of an algorithm?

    Designing an algorithm that solves the problem is only the first step; we also need to judge which algorithm is better. Usually we evaluate from two dimensions:

    1. Time complexity

    It measures howthe time required for the algorithm to rungrows withthe input data size (n) . We care not about specific seconds, but about the growth trend (called asymptotic time complexity)。

    Comparison of common time complexities:

    Complexity Name Example (n = data size) Vivid analogy
    O(1) Constant order Array access by index "Turning on a light". No matter how large the room, the time to press the switch is the same.
    O(log n) Logarithmic order Binary Search "Flipping through a dictionary". Each time half is eliminated, making the search very fast.
    O(n) Linear order Iterate over the array "Counting people". Counting one person at a time; time is proportional to the total number of people.
    O(n log n) Linearithmic order Quicksort, merge sort "Divide-then-conquer sorting". Much faster than O(n2).
    O(n²) Quadratic order Simple selection sort, bubble sort "Pairwise handshakes". Everyone must shake hands with everyone else once.
    O(2ⁿ) Exponential order Solving the Tower of Hanoi, brute-force enumeration "Cell division". The growth is terrifying; slightly larger n becomes unbearable.

    How to analyze? Focus on loops and recursion.

    2. Space complexity

    It measures howThe memory space required for the algorithm to rungrows withthe input data size (n) grows with the input size. Besides storing the input data itself, one must also consider extra arrays, variables, etc. allocated during the algorithm's execution.

    Example analysis:

    Example

    Example 1: space complexity O(1)

    def

    find_max_in_list

    (

    lst

    )

    :

        max_val

    =

    lst

    [

    0

    ]

             

    Only a constant number of extra variables used

       

    for

    num

    in

    lst:

           

    if

    num

    max_val:

                max_val

    =

    num

       

    return

    max_val

    Example 2: space complexity O(n)

    def

    copy_and_double_list

    (

    lst

    )

    :

        new_list

    =

    [

    ]

               

    Allocated a new list of the same length as the input list

       

    for

    num

    in

    lst:

            new_list.

    append

    (

    num *

    2

    )

       

    return

    new_list


    Practical exercise: understanding analysis and application through sorting algorithms

    Let's take the classic Bubble Sort as an example and apply the above knowledge comprehensively.

    Algorithm idea

    Repeatedly traverse the list to be sorted, comparing two adjacent elements at a time, and swap them if they are in the wrong order.

    The traversal is repeated until no more swaps are needed, meaning the list is sorted. Smaller elements gradually float to the top of the sequence like bubbles.

    Python implementation and line-by-line analysis

    Example

    def

    bubble_sort

    (

    arr

    )

    :

       

    """
        Bubble sort algorithm
        Parameter arr: the list to be sorted
        Return value: the sorted list (modified in place, also returned directly)
        """

        n

    =

    len

    (

    arr

    )

       

    Outer loop: controls how many rounds of "bubbling" are needed in total

       

    for

    i

    in

    range

    (

    n -

    1

    )

    :

           

    Assume this round is already sorted, for optimization

            swapped

    =

    False

           

    Inner loop: performs one round of bubbling, sinking the largest element to the end

           

    After each round, the last i+1 elements are sorted, so the range is n-1-i

           

    for

    j

    in

    range

    (

    0

    ,

    n -

    1

    )

    :

               

    If the earlier element is larger than the later one, swap

               

    if

    arr

    [

    j

    ]

    arr

    [

    j +

    1

    ]

    :

                    arr

    [

    j

    ]

    ,

    arr

    [

    j +

    1

    ]

    =

    arr

    [

    j +

    1

    ]

    ,

    arr

    [

    j

    ]

     

    Python's elegant swap syntax

                    swapped

    =

    True

     

    A swap occurred

           

    If no swap occurs in a round, the list is fully sorted; end early

           

    if

    not

    swapped:

               

    break

       

    return

    arr

    Test data and verification

    test_data

    =

    [

    64

    ,

    34

    ,

    25

    ,

    12

    ,

    22

    ,

    11

    ,

    90

    ]

    print

    (

    "Before sorting:"

    ,

    test_data

    )

    sorted_data

    =

    bubble_sort

    (

    test_data.

    copy

    (

    )

    )

    Use copy to prevent the original list from being modified

    print

    (

    "After sorting:"

    ,

    sorted_data

    )

    Verify the result is correct

    print

    (

    "Is the sorting correct?"

    ,

    sorted_data

    ==

    sorted

    (

    test_data.

    copy

    (

    )

    )

    )

    Should match Python's built-in sorting result

    Output result:

    排序前: [64, 34, 25, 12, 22, 11, 90]
    排序后: [11, 12, 22, 25, 34, 64, 90]
    排序是否正确? True
    

    Algorithm analysis

    - **Worst and average case O(n2)**: When the list is completely reversed, it requires `(n-1) + (n-2) + ... + 1 = n(n-1)/2` comparisons and swaps. - **Best case O(n)**: When the list is already sorted, with the `swapped` flag optimization, only one traversal is needed to detect no swaps and end early.

    Exercise tasks