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:
- Linear structures: arrays, linked lists, stacks, queues
- Non-linear structures: trees, graphs, heaps, hash tables
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:
- Basic algorithms: traversal, recursion, divide and conquer
- Sorting and searching: quicksort, mergesort, binary search
- Advanced strategies: greedy, dynamic programming, backtracking
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
- Data: a collection of symbols that a computer can recognize, store, and process, such as numbers and characters.
- Data Element: the basic unit of data, usually considered and processed as a whole in a program.
- data item: the smallest indivisible unit that makes up a data element and has independent meaning.
- Data Structure: a collection of data elements that have one or more specific relationships with each other.
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:
- Linear structure: there is a "one-to-one" linear relationship between data elements, e.g., arrays, linked lists, stacks, queues.
- Non-linear structure: there is a complex "one-to-many" or "many-to-many" relationship between data elements, e.g., trees, graphs, sets.
Physical structure(also called storage structure) describes how data is actually stored in a computer's memory. It is mainly divided into:
- Sequential storage: logically adjacent elements are stored in storage units that are also physically adjacent, e.g., arrays.
- Linked storage: logically adjacent elements are not required to be physically adjacent; the logical relationships between elements are represented by additional pointers, e.g., linked lists.
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:
- Finiteness: an algorithm must terminate after a finite number of steps.
- Definiteness: every step of an algorithm must be precisely defined, without ambiguity.
- Feasibility: every step of an algorithm can be realized by executing already implemented basic operations a finite number of times.
- Input: an algorithm has zero or more inputs.
- 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.
- Time Complexity: qualitatively describes the running time of an algorithm. It represents the growth trend of the algorithm's execution time as the problem size n increases, commonly expressed using Big O notation.
- Space complexity: qualitatively describes the amount of temporary storage space an algorithm occupies during execution, also expressed using Big O notation.
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.
- Data Structure: an array (a sequentially stored linear list).
- Algorithm: starting from the first element, compare with the target value one by one until found or all elements are traversed.
- Time Complexity: O(n). In the worst case, all n elements must be checked.
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
:
(
f
"The index of target number {target_number} in the array is: {result}"
)
else
:
(
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.
- Data Structure: a sorted array.
- Algorithm:
- Time Complexity: O(log n). Each comparison halves the search range.
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
(
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
:
(
f
"The index of target number {target_number} in the sorted array is: {result}"
)
else
:
(
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:
- When
n=1000, linear search needs at most 1000 comparisons, while binary search needs at most about 10 comparisons (because 2^10 ≈ 1024). - Binary search is far more efficient than linear search, but it requires the data to be pre-sorted. Sorting itself has a cost, so which algorithm to choose depends on the specific scenario (e.g., whether the data is static with frequent lookups, or dynamic with frequent insertions).
How to get started?
Learning data structures and algorithms is a step-by-step process; the following path is recommended:
- 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.
- Start with basic data structures:
- Learn basic algorithm ideas:
- Tackle non-linear structures:
- 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.