Python Bubble Sort
Bubble sort is a simpleexchange sorting algorithm; its core working principle is:
- repeatedly traverse the list to be sorted, each time comparingtwo adjacent elements;
- if the two elements are out of order (for example, in an ascending sort the previous element is greater than the next), thenswap their positions;
- each pass bubbles thelargest element of the current unsorted part to the end(in the ascending case), just like bubbles rising;
- repeat the above process until the whole list is fully sorted (no swaps occur or all elements have been traversed).

Key characteristics
- Sorting type: exchange sort
- Time complexity: worst case O(n²) (list completely reversed), average case O(n²), best case O(n) (optimized version, list already sorted)
- Space complexity: O(1) (in-place sorting, no extra auxiliary space)
- Stability: stable sort (the relative order of equal elements does not change)
Example
def
bubbleSort
(
arr
)
:
n
=
len
(
arr
)
Traverse all array elements
for
i
in
range
(
n
)
:
The last i elements are already in their correct positions (no need to compare again)
for
j
in
range
(
0
,
n
i
1
)
:
if
arr
[
j
]
arr
[
j
1
]
:
arr
[
j
]
,
arr
[
j
1
]
=
arr
[
j
1
]
,
arr
[
j
]
arr
=
[
64
,
34
,
25
,
12
,
22
,
11
,
90
]
bubbleSort
(
arr
)
(
"
Sorted array:
"
)
for
i
in
range
(
len
(
arr
)
)
:
(
"
%d
"
%
arr
[
i
]
)
,
The output of the code above is:
Sorted array:
11
12
22
25
34
64
90
Python3 Examples