Insertion Sort
This page provides a brief introduction to insertion sort.
Definition
Insertion sort is a simple and intuitive sorting algorithm. Its working principle is to divide the elements to be sorted into two parts: "sorted" and "unsorted". Each time, it selects one element from the "unsorted" part and inserts it into the correct position within the "sorted" part.
An operation similar to insertion sort is when playing poker: you draw a card from the table, insert it into your hand in order of rank, and then draw the next card.
Properties
Stability
Insertion sort is a stable sorting algorithm.
Time Complexity
The best-case time complexity of insertion sort is \(O(n)\), which is highly efficient when the sequence is almost sorted.
The worst-case and average-case time complexities of insertion sort are both \(O(n^2)\).
Code Implementation
Pseudocode
1 2 3 4 5 6 7 8 9 10 11 | |
1 2 3 4 5 6 7 8 | |
1 2 3 4 5 6 7 8 9 10 11 | |
Binary Insertion Sort
Insertion sort can also be optimized using binary search, which significantly improves performance when sorting a large number of elements.
Time Complexity
The basic idea of binary insertion sort is the same as that of direct insertion sort. Binary insertion sort only optimizes the constant factor in the time complexity of insertion sort, so the optimized time complexity remains unchanged.
Code Implementation
1 2 3 4 5 6 7 8 9 10 | |
本页面最近更新:,更新历史
发现错误?想一起完善? 在 GitHub 上编辑此页!
本页面贡献者:OI-wiki
本页面的全部内容在 CC BY-SA 4.0 和 SATA 协议之条款下提供,附加条款亦可能应用