Insertion Sort
Insertion Sort, also commonly called direct insertion sort, is an effective algorithm for sorting a small number of elements.
Insertion sort is one of the simplest sorting methods. Its basic idea is to insert a record into an already sorted ordered list, thereby producing a new ordered list with one more record.
Its implementation uses a double loop: the outer loop iterates over all elements except the first, and the inner loop searches for the insertion position in the ordered list before the current element and performs shifting.

How It Works
The core idea of insertion sort is "build an ordered sequence". It logically divides the array (or list) to be sorted into two parts:
- Sorted portion: Initially, the first element of the array is usually considered an ordered sequence by itself.
- Unsorted portion: From the second element to the last element.
The algorithm will repeatedly insert the first element of the unsorted portion into the correct position in the sorted portion, until the unsorted portion is empty and the entire array becomes ordered.
Applicability Notes
The average time complexity of insertion sort is also O(n^2), and its space complexity is constant order O(1); the specific time complexity is also related to how ordered the array is.
In insertion sort, when the array to be sorted is already ordered, it is the best case: the current number only needs to be compared with the previous number, requiring N-1 comparisons in total, with time complexity O(N). The worst case is when the array is in reverse order, requiring the most comparisons; the worst case is O(n^2).
Process Diagram
Assume the first n-1 (where n>=2) numbers are already sorted, and now the n -th number is inserted into the previously sorted sequence, and its appropriate position is found so that the sequence with the n-th number inserted is also sorted.
The process of inserting all elements in this way until the entire sequence is ordered is called insertion sort.
The entire process of insertion sort from smallest to largest is shown in the figure:
**First round:** Start comparing from the 6 at the second position; it is smaller than the 7 before it, so swap positions.

**Second round:** The 9 at the third position is larger than the 7 at the previous position, so no swap is needed.

**Third round:** The 3 at the fourth position is smaller than the 9 at the previous position, so swap and continue comparing forward.

**Fourth round:** The 1 at the fifth position is smaller than the 9 at the previous position, so swap positions and continue comparing forward.

......
Continue comparing in this way up to the last element.
Java Example Code
Source code package download:Download
Partial code:
InsertionSort.java file code:
package
runoob
;
/**
* Insertion sort
*/
public
class
InsertionSort
{
// Core code---start
public
static
void
sort
(
Comparable
[
]
arr
)
{
int
n
=
arr.
length
;
for
(
int
i
=
0
;
i
<
n
;
i
++
)
{
// Find the appropriate insertion position for element arr[i]
for
(
int
j
=
i
;
j
0
;
j
--
)
if
(
arr
[
j
]
.
compareTo
(
arr
[
j
1
]
)
<
0
)
swap
(arr, j , j
1
)
;
else
break
;
}
}
// Core code---end
private
static
void
swap
(
Object
[
]
arr,
int
i,
int
j
)
{
Object
t
=
arr
[
i
]
;
arr
[
i
]
=
arr
[
j
]
;
arr
[
j
]
=
t
;
}
public
static
void
main
(
String
[
]
args
)
{
int
N
=
20000
;
Integer
[
]
arr
=
SortTestHelper.
generateRandomArray
(
N,
0
,
100000
)
;
InsertionSort.
sort
(
arr
)
;
for
(
int
i
=
0
;
i
<
arr.
length
;
i
++
)
{
System
.
out
.
(
arr
[
i
]
)
;
System
.
out
.
(
' '
)
;
}
}
}
Algorithm Implementation and Code Analysis
After understanding the principle, let's look at the specific code implementation. Versions in two common languages, Python and Java, are provided here.
Python Implementation
Example
def
insertion_sort
(
arr
)
:
"""
Insertion sort algorithm implementation (ascending order)
:param arr: the list to be sorted
:return: The sorted list (modified in place, also returned)
"""
Traverse from the second element to the last element (indices 1 to n-1)
for
i
in
range
(
1
,
len
(
arr
)
)
:
current_value
=
arr
[
i
]
The current element to be inserted, first "hold it in hand"
j
=
i -
1
j points to the last element of the sorted sequence
Inner loop: find the insertion position for current_value in the sorted portion arr[0..i-1]
Condition 1: j >= 0 ensures no out-of-bounds before the head of the list
Condition 2: arr[j] > current_value means the currently compared element is larger than the one "in hand" and needs to be moved back
while
j
=
0
and
arr
[
j
]
current_value:
arr
[
j +
1
]
=
arr
[
j
]
Move the larger element one position back to make room
j -
=
1
Continue comparing the next element to the left
The loop ends, indicating the insertion position (j+1) has been found
At this point arr[j] <= current_value or j == -1
arr
[
j +
1
]
=
current_value
Insert the "held" element into the correct position
return
arr
Test code
if
name
==
"main"
:
Test Data
test_data
=
[
64
,
34
,
25
,
12
,
22
,
11
,
90
]
(
"Before sorting:"
,
test_data
)
sorted_data
=
insertion_sort
(
test_data.
copy
(
)
)
Sort using a copy, without affecting the original data
(
"After sorting:"
,
sorted_data
)
Another test: basically ordered data
nearly_sorted_data
=
[
1
,
3
,
2
,
4
,
6
,
5
,
8
,
7
]
(
"\nBefore sorting basically ordered data:"
,
nearly_sorted_data
)
(
"After sorting basically ordered data:"
,
insertion_sort
(
nearly_sorted_data.
copy
(
)
)
)
Java implementation
Example
public
class
InsertionSort
{
public
static
void
insertionSort
(
int
[
]
arr
)
{
// Traverse from the second element to the last element (indices 1 to n-1)
for
(
int
i
=
1
;
i
<
arr.
length
;
i
++
)
{
int
currentValue
=
arr
[
i
]
;
// The current element to be inserted
int
j
=
i
1
;
// j points to the last element of the sorted sequence
// Inner loop: find the insertion position and move elements
while
(
j
=
0
&&
arr
[
j
]
currentValue
)
{
arr
[
j
1
]
=
arr
[
j
]
;
// Move elements back
j
--;
}
// Insert the current element into the correct position
arr
[
j
1
]
=
currentValue
;
}
}
// Overloaded method, supports sorting a portion of an integer array
public
static
void
insertionSort
(
int
[
]
arr,
int
left,
int
right
)
{
for
(
int
i
=
left
1
;
i
<=
right
;
i
++
)
{
int
currentValue
=
arr
[
i
]
;
int
j
=
i
1
;
while
(
j
=
left
&&
arr
[
j
]
currentValue
)
{
arr
[
j
1
]
=
arr
[
j
]
;
j
--;
}
arr
[
j
1
]
=
currentValue
;
}
}
public
static
void
main
(
String
[
]
args
)
{
// Test data
int
[
]
testData
=
{
64
,
34
,
25
,
12
,
22
,
11
,
90
}
;
System
.
out
.
(
"Before sorting: "
)
;
printArray
(
testData
)
;
int
[
]
dataToSort
=
testData.
clone
(
)
;
// Use a copy
insertionSort
(
dataToSort
)
;
System
.
out
.
(
"After sorting: "
)
;
printArray
(
dataToSort
)
;
}
private
static
void
printArray
(
int
[
]
arr
)
{
for
(
int
num
:
arr
)
{
System
.
out
.
(
num
" "
)
;
}
System
.
out
.
println
(
)
;
}
}
Analysis of Algorithm Characteristics
Understanding an algorithm's performance and application scenarios is essential. The characteristics of insertion sort can be summarized as follows:
| Feature | Description | Explanation |
|---|---|---|
| Time Complexity | Average and worst case: $O(n^2)$ | Nested loops are needed to compare and move elements. For n elements, in the worst case (completely reversed), about $\frac{n(n-1)}{2}$ comparisons and moves are needed. |
| Best Case:$O(n)$ | When the input array is already basically ordered, the inner loop rarely executes or exits immediately, requiring only n-1 comparisons. | |
| Space complexity | $O(1)$ | Is in-place sort algorithm requires only constant-level extra space (such as current_value, j and other variables). |
| Stability | Stable | When two elements are equal, their relative order remains unchanged after sorting. This is because the algorithm only moves elements when encountering Greater than the current value. |
| Applicable scenarios | 1. Small-scale data |
2. 数据基本有序
3. 作为高级排序算法(如快速排序、归并排序)的子过程 | 在这些情况下,其简单的逻辑和低常数开销使其表现可能优于更复杂的 $O(n \log n)$ 算法。 |
Derivation of the time complexity formula (worst case)
In the worst case (array completely reversed):
- The 1st element (index 0) is inserted with 0 comparisons.
- The 2nd element (index 1) is inserted with 1 comparison and 1 move.
- The 3rd element (index 2) is inserted with 2 comparisons and 2 moves.
- ...
- The n-th element (index n-1) is inserted with n-1 comparisons and n-1 moves.
The total number of comparisons and moves is: $0 + 1 + 2 + ... + (n-1) = \frac{n(n-1)}{2}$
Therefore, the time complexity is $O(n^2)$.