Algorithm fundamentals
An algorithm is a clear, finite sequence of steps for solving a specific problem.
Understanding the basic concepts of algorithms and efficiency analysis is an important prerequisite for studying data structures and algorithms.
Definition and characteristics of algorithms
In computer science, an algorithm is a finite sequence of instructions, each representing one or more operations.
A qualified algorithm must possess the following five basic characteristics:
| Feature | Meaning | Counter-example |
|---|---|---|
| Input | Has zero or more external inputs | Having no input is also valid, e.g. generating random numbers |
| Output | Produces at least one result | An 'algorithm' with no output is meaningless |
| Definiteness | The meaning of each step must be clear and unambiguous | Vague descriptions like 'add appropriately' are unacceptable |
| Finiteness | Must terminate within a finite number of steps, no infinite loops | An operating system itself is not an algorithm, as it theoretically runs forever |
| Feasibility | Each step can be realized through basic operations | 'Dividing by zero' is infeasible, and so is 'sorting in one step' |
An algorithm's 'finiteness' does not contradict a program's 'infinite loop'. A program may get stuck in an infinite loop due to a bug, but the algorithm itself must terminate in finite steps. The difference: an algorithm is a concept at the 'design intent' level, while a program is at the 'actual execution' level.
Representations of algorithms
When designing and communicating algorithms, two common representations are used.
Pseudocode
Pseudocode uses text close to natural language but with a structured format to describe algorithm logic.
It does not depend on specific programming language syntax, making it easy to express ideas quickly.
For example, pseudocode to find the maximum value in a set of numbers:
算法:FindMax
输入:数组 A,长度 n
输出:A 中的最大值
1. max = A[0]
2. for i = 1 to n-1:
3. if A[i] > max:
4. max = A[i]
5. return max
Flowchart
A flowchart visually presents the execution flow of an algorithm through graphical means.

The figure above shows the complete execution flow of the FindMax algorithm: start from the input array, initialize the current maximum, then compare each element in turn, updating the maximum if a larger value is found, and output the result after traversal.
Symbol conventions in flowcharts:
| Symbol shape | Meaning |
|---|---|
| Rounded rectangle (or ellipse) | Start / End |
| Rectangle | Processing step |
| Diamond | Decision / branch |
| Parallelogram | Input / Output |
| Arrow | Flow direction |
Algorithm efficiency analysis
After designing an algorithm, its efficiency must also be evaluated. This is mainly measured along two dimensions.
Time Complexity
Time complexity describes: as the input size n grows, the growth trend of the number of basic operations the algorithm requires.
Note that we care about the 'growth trend', not the 'exact number of executions'. For large inputs, differences in constant multiples matter far less than differences in growth trend.
Space complexity
Space complexity describes: as input size n grows, the growth trend of extra memory space required during execution.
The 'extra' space here means how much auxiliary space the algorithm needs beyond storing the input data itself.
Time and space are often a pair of contradictions — trading space for time, or time for space, is a common trade-off in algorithm design. For example: hash tables trade extra storage for O(1) lookup time; in-place sorting algorithms avoid extra space at the cost of slightly more computation steps.
Big O notation
Big O notation is the most commonly used mathematical tool for measuring time and space complexity.
It describes the upper bound of the growth trend of running time or space usage as input size n increases, in the worst case.
Definition: if there exist positive constants c and n0 such that for n >= n0, T(n) <= c * f(n) always holds, then we write T(n) = O(f(n)).
Plain understanding: Big O notation ignores constant factors and low-order terms, focusing only on the fastest-growing term.
For example: if an algorithm needs 3n^2 + 100n + 500 operations, when n is large enough the n^2 term dominates growth, so we say it is O(n^2).
Common complexity levels
The figure above visually shows the growth trend of each complexity level as input size n increases.
| Notation | Name | n=10 | n=1000 | Typical algorithms |
|---|---|---|---|---|
| O(1) | Constant order | 1 | 1 | Array access by index, hash table lookup |
| O(log n) | Logarithmic order | ~3 | ~10 | Binary search, balanced BST operations |
| O(n) | Linear order | 10 | 1000 | Linear search, array traversal |
| O(n log n) | Linearithmic order | ~30 | ~10000 | Merge sort, quicksort (average) |
| O(n²) | Quadratic order | 100 | 1000000 | Bubble sort, selection sort |
| O(2ⁿ) | Exponential order | 1024 | Astronomical | Brute-force subset enumeration |
From the table, when n=1000, O(1) still needs only 1 operation, O(n) needs 1000, and O(n^2) needs 1,000,000.
In large-scale data scenarios, choosing an algorithm of the right complexity can yield order-of-magnitude performance differences.
In practice, try to keep core algorithm complexity at or below O(n log n). When complexity reaches O(n^2) or higher, pay extra attention to whether the input size is controllable and whether a better alternative exists.
Time complexity calculation example
Below is a simple C code snippet and its time complexity analysis:
Example
#include
/* Function: compute the sum of array elements
Time complexity: O(n)
n is the array length; the loop runs n times, each iteration doing constant operations */
int
sumArray
(
int
arr
[
]
,
int
n
)
{
int
total
=
0
;
/* O(1) — assignment operation, executed once */
for
(
int
i
=
0
;
i
<
n
;
i
++
)
{
/* Loop body */
total
+=
arr
[
i
]
;
/* O(1) — addition and assignment, executed n times */
}
return
total
;
/* O(1) — return operation, executed once */
}
/* Overall time complexity: O(1 + n + 1) = O(n)
Low-order constant terms are ignored */
int
main
(
)
{
int
nums
[
]
=
{
5
,
10
,
15
,
20
,
25
}
;
int
size
=
sizeof
(
nums
)
/
sizeof
(
nums
[
0
]
)
;
int
result
=
sumArray
(
nums
,
size
)
;
printf
(
"Sum of array elements: %d\n"
,
result
)
;
/* Output: sum of array elements: 75 */
return
0
;
}
Here is another example with nested loops:
Example
#include
/* Function: print an n x n multiplication table
Time complexity: O(n^2)
Outer loop runs n times, inner loop runs n times, total n x n times */
void
printMulTable
(
int
n
)
{
for
(
int
i
=
1
;
i
<=
n
;
i
++
)
{
/* Outer loop O(n) */
for
(
int
j
=
1
;
j
<=
n
;
j
++
)
{
/* Inner loop O(n), total after nesting n^2 */
printf
(
"%d\t"
,
i
j
)
;
/* O(1) operation */
}
printf
(
"\n"
)
;
}
}
/* Overall time complexity: O(n x n) = O(n^2) */
int
main
(
)
{
printMulTable
(
5
)
;
/* Output 5 x 5 multiplication table */
return
0
;
}
Space complexity calculation example
Space complexity focuses on the extra memory space allocated during algorithm execution.
Example
#include
#include
/* Function: create a new array storing the squares of the original array
Space complexity: O(n) — allocates a new array of length n */
int
squareArray
(
int
arr
[
]
,
int
n
)
{
int
result
=
(
int
)
malloc
(
n
sizeof
(
int
)
)
;
/* Allocate extra space for n ints */
if
(
result
==
NULL
)
{
return
NULL
;
/* Return NULL if malloc fails */
}
for
(
int
i
=
0
;
i
<
n
;
i
++
)
{
result
[
i
]
=
arr
[
i
]
arr
[
i
]
;
}
return
result
;
}
/* Space complexity O(n):
- The input array arr is not counted (it belongs to the input itself)
- The result array allocates n extra ints, which is extra space
- Variable i is constant space O(1), dominated by O(n) */
int
main
(
)
{
int
nums
[
]
=
{
1
,
2
,
3
,
4
,
5
}
;
int
n
=
5
;
int
squared
=
squareArray
(
nums
,
n
)
;
if
(
squared
!=
NULL
)
{
for
(
int
i
=
0
;
i
<
n
;
i
++
)
{
printf
(
"%d "
,
squared
[
i
]
)
;
/* Output: 1 4 9 16 25 */
}
printf
(
"\n"
)
;
free
(
squared
)
;
/* Manually free dynamically allocated memory */
}
return
0
;
}
Common beginner misconception: time and space complexity analyze 'growth trends' rather than exact values. Constant coefficients, low-order terms, and differences between programming languages are all ignored by Big O notation. Therefore O(2n) and O(n) are equivalent — both represent linear growth.