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

Introduction to Data Structures and Algorithms

Introduction to Data Structures and Algorithms

In computer science, data structures and algorithms are the core foundation for building efficient and reliable software. They are the toolbox programmers use to solve complex problems, determining a program's running speed and resource consumption.

Imagine you are organizing a messy bookshelf. If you just pile the books randomly, finding a specific book would be very difficult. But if you sort them by the first letter of the title, or categorize them (such as fiction, history, science), search efficiency improves greatly.Data Structureis like the method of organizing a bookshelf; it defines how data should be organized and stored. AndAlgorithmare the specific steps for finding, inserting, or deleting a book.

Data structures and algorithms are the underlying capabilities of computer science, used to solve two things: how data is organized and how problems are solved efficiently.

Data Structure
studies how data is organized in memory or storage, and how to access and modify it efficiently. The core goal is to reduce time and space costs.
Common types:

Algorithm
studies the steps and strategies for solving problems; essentially it is an abstraction of the computation process. There are only two evaluation criteria: time complexity and space complexity.
Common classifications:

Relational
Data structures decide how to store, algorithms decide how to compute. For the same problem, different structures can lead to vastly different algorithmic complexity.


Data Structure

A data structure is the way a computer stores and organizes data.

A data structure aims to implement a collection of data elements with one or more specific relationships, along with a set of operations defined on that data.

Core Concepts

Classification of data structures

Data structures are mainly divided into two categories:Logical structureandPhysical structure。

Logical structuredescribes the abstract relationships between data elements, independent of how the computer implements them. It is mainly divided into:

Physical structure(also called storage structure) describes how data is actually stored in a computer's memory. It is mainly divided into:


Algorithm

An algorithm is a series of clear, finite instruction steps for solving a specific problem.

An effective algorithm should have the following five properties:

  1. Finiteness: an algorithm must terminate after a finite number of steps.
  2. Definiteness: every step of an algorithm must be precisely defined, without ambiguity.
  3. Feasibility: every step of an algorithm can be realized by executing already implemented basic operations a finite number of times.
  4. Input: an algorithm has zero or more inputs.
  5. Output: an algorithm has one or more outputs, which are quantities with a specific relationship to the inputs.

Evaluation criteria for algorithms: time complexity and space complexity

How do we judge whether an algorithm is good or bad? Usually fromTimeandSpacetwo dimensions.

Comparison of Common Time Complexities

The following table shows how different time complexities grow with data size:

Complexity notation Name Example (n=10 vs n=1000) Description
O(1) Constant order 1 step vs 1 step most efficient, independent of problem size
O(log n) Logarithmic order ~3 steps vs ~10 steps very efficient, e.g., binary search
O(n) Linear order 10 steps vs 1000 steps good efficiency, e.g., traversing an array
O(n log n) Linearithmic order ~30 steps vs ~10000 steps fairly efficient, e.g., quicksort
O(n²) Quadratic order 100 steps vs 1,000,000 steps less efficient, e.g., simple selection sort
O(2ⁿ) Exponential order 1024 steps vs an astronomical number very inefficient, should be avoided

A simple understanding: we seek algorithms whose execution time grows more slowly as the data size n increases. O(1) and O(log n) are excellent, O(n) is acceptable, while O(n²) and above need optimization for large data sets.


Classic Data Structure and Algorithm Examples

Let's feel the application of data structures and algorithms through a concrete problem.

Problem: in an unordered list of numbers, quickly determine whether a certain target number exists.

Solution 1: Linear Search (using an array)

This is an intuitive but inefficient method.

Example

Linear Search Algorithm Example

def

linear_search

(

arr

,

target

)

:

   

"""
    Linearly search for the target value `target` in the array `arr`.
    Parameters:
        arr: the list to search
        target: the target value to find
    Returns:
        If found, return its index; otherwise return -1.
    """

   

for

i

in

range

(

len

(

arr

)

)

:  

Traverse each element of the array

       

if

arr

[

i

]

==

target:  

If the current element equals the target value

           

return

i          

Return the current index

   

return

1

                 

Traversal complete without finding it, return -1

Test Data

test_data

=

[

12

,

45

,

67

,

89

,

34

,

23

,

90

,

11

]

target_number

=

34

Perform the search

result

=

linear_search

(

test_data

,

target_number

)

Output result

if

result

!=

1

:

   

print

(

f

"The index of target number {target_number} in the array is: {result}"

)

else

:

   

print

(

f

"Target number {target_number} not found in the array"

)

Output result:

目标数字 34 在数组中的索引是:4

Solution 2: Binary Search (using a sorted array)

This is an efficient method, but it requires the data to be sorted.

  • Compare the target value with the middle element of the array.
  • If they are equal, it is found.
  • If the target value is smaller, repeat step 1 on the left half of the array.
  • If the target value is larger, repeat step 1 on the right half of the array.
  • If the search interval is empty, it is not found.
  • 1. Compare the target value with the middle element of the array. 2. If they are equal, it is found. 3. If the target value is smaller, repeat step 1 on the left half of the array. 4. If the target value is larger, repeat step 1 on the right half of the array. 5. If the search interval is empty, it is not found.

    Example

    Binary Search Algorithm Example (assuming the input array is sorted)

    def

    binary_search

    (

    sorted_arr

    ,

    target

    )

    :

       

    """
        Binary search for the target value `target` in the sorted array `sorted_arr`.
        Parameters:
            sorted_arr: the sorted list (ascending order)
            target: the target value to find
        Returns:
            If found, return its index; otherwise return -1.
        """

        left

    ,

    right

    =

    0

    ,

    len

    (

    sorted_arr

    )

    1

     

    Initialize the search interval to the entire array

       

    while

    left

    <=

    right:                  

    Continue searching while the interval is valid

            mid

    =

    (

    left + right

    )

    //

    2

           

    Compute the middle index

           

    if

    sorted_arr

    [

    mid

    ]

    ==

    target:    

    Target value found

               

    return

    mid

           

    elif

    sorted_arr

    [

    mid

    ]

    <

    target:  

    Target value is in the right half

                left

    =

    mid +

    1

           

    else

    :                            

    Target value is in the left half

                right

    =

    mid -

    1

       

    return

    1

                               

    Interval invalid, not found

    Test data (must be sorted)

    test_data

    =

    [

    12

    ,

    45

    ,

    67

    ,

    89

    ,

    34

    ,

    23

    ,

    90

    ,

    11

    ]

    sorted_test_data

    =

    sorted

    (

    test_data

    )

     

    Sort the test data

    print

    (

    f

    "Sorted array: {sorted_test_data}"

    )

    target_number

    =

    34

    Perform the search

    result

    =

    binary_search

    (

    sorted_test_data

    ,

    target_number

    )

    Output result

    if

    result

    !=

    1

    :

       

    print

    (

    f

    "The index of target number {target_number} in the sorted array is: {result}"

    )

    else

    :

       

    print

    (

    f

    "Target number {target_number} not found in the sorted array"

    )

    Output result:

    有序数组:[11, 12, 23, 34, 45, 67, 89, 90]
    
    目标数字 34 在有序数组中的索引是:3
    
    

    Comparison and Reflection:


    How to get started?

    Learning data structures and algorithms is a step-by-step process; the following path is recommended:

    1. Master a programming language: first you need a tool to implement your ideas; Python, Java, or C++ are all good choices. Python's concise syntax is more suitable for beginners to focus on the algorithm logic itself.
    2. Start with basic data structures:
    3. Array / List: the most basic and commonly used sequential storage structure.
    4. Linked list: key to understanding pointers/references and dynamic memory allocation.
    5. Stacks and Queues: understand the operation-restricted linear lists of "last in, first out" and "first in, first out".
    6. - **Array / List**: the most basic and commonly used sequential storage structure. - **Linked List**: key to understanding pointers/references and dynamic memory allocation. - **Stacks and Queues**: understand the operation-restricted linear lists of "last in, first out" and "first in, first out".
      1. Learn basic algorithm ideas:
      2. Sorting algorithms: bubble sort, selection sort, insertion sort (understand O(n²)), then learn mergesort and quicksort (understand O(n log n) and the divide-and-conquer idea).
      3. Searching algorithms: sequential search, binary search.
      4. - **Sorting algorithms**: bubble sort, selection sort, insertion sort (understand O(n²)), then learn mergesort and quicksort (understand O(n log n) and the divide-and-conquer idea). - **Searching algorithms**: sequential search, binary search.
        1. Tackle non-linear structures:
        2. Trees: focus on binary trees, especially binary search trees. Understand tree traversals (preorder, inorder, postorder).
        3. Graph: understand graph representations (adjacency matrix, adjacency list) and basic traversal algorithms (depth-first search DFS, breadth-first search BFS).
        4. - **Trees**: focus on binary trees, especially binary search trees. Understand tree traversals (preorder, inorder, postorder). - **Graphs**: understand graph representations (adjacency matrix, adjacency list) and basic traversal algorithms (depth-first search DFS, breadth-first search BFS).
          1. Practice and solve problems: practice on platforms like LeetCode and Nowcoder starting with easy problems, applying theory to practice — this is the best way to consolidate knowledge and sharpen your thinking.