Implementing Bubble Sort in Python
Bubble sort is a simple sorting algorithm that repeatedly traverses the list to be sorted, comparing adjacent elements and swapping them until the whole list is sorted. The algorithm is named after the way smaller elements slowly "float" to the top of the sequence through swapping.
The code:
Example
def
bubble_sort
(
arr
)
:
n
=
len
(
arr
)
for
i
in
range
(
n
)
:
for
j
in
range
(
0
,
n-i-
1
)
:
if
arr
[
j
]
arr
[
j+
1
]
:
arr
[
j
]
,
arr
[
j+
1
]
=
arr
[
j+
1
]
,
arr
[
j
]
Example array
arr
=
[
64
,
34
,
25
,
12
,
22
,
11
,
90
]
bubble_sort
(
arr
)
(
"Sorted array:"
,
arr
)
Code analysis:
bubble_sortThe function takes a listarras its argument.nis the length of the list.- The outer loop
for i in range(n)controls the number of passes; after each pass the largest element is placed in its correct position. - The inner loop
for j in range(0, n-i-1)compares adjacent elements and swaps them if the previous one is greater than the next. - Finally, print the sorted array.
Output result:
排序后的数组: [11, 12, 22, 25, 34, 64, 90]
Python3 Examples