Bubble Sort
This page provides a brief introduction to bubble sort.
Definition
Bubble sort is a simple sorting algorithm. During the execution of the algorithm, smaller elements gradually "float" to the top of the sequence like bubbles, hence the name bubble sort.
Process
Its working principle is to check two adjacent elements each time. If the preceding element and the following element satisfy the given sorting condition, the two adjacent elements are swapped. When no adjacent elements need to be swapped, the sorting is complete.
After \(i\) scans, the last \(i\) elements of the sequence must be the largest \(i\) elements. Therefore, bubble sort requires at most \(n-1\) scans of the array to complete the sorting.
Properties
Stability
Bubble sort is a stable sorting algorithm.
Time Complexity
When the sequence is completely sorted, bubble sort only needs to traverse the array once without performing any swap operations, with a time complexity of \(O(n)\).
In the worst case, bubble sort performs \(\frac{(n-1)n}{2}\) swap operations, with a time complexity of \(O(n^2)\).
The average time complexity of bubble sort is \(O(n^2)\).
Code Implementation
Pseudocode
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | |
1 2 3 4 5 6 7 8 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | |
本页面最近更新:,更新历史
发现错误?想一起完善? 在 GitHub 上编辑此页!
本页面贡献者:OI-wiki
本页面的全部内容在 CC BY-SA 4.0 和 SATA 协议之条款下提供,附加条款亦可能应用