"""冒泡排序"""
class BubbleSort(object):
def __init__(self
, li
):
self
.li
= li
def campare_elem(self
, m
, n
):
"""比较两个元素的大小"""
if self
.li
[m
] > self
.li
[n
]:
self
.exchange_elem
(m
, n
)
def exchange_elem(self
, m
, n
):
"""交换元素位置"""
self
.li
[m
], self
.li
[n
] = self
.li
[n
], self
.li
[m
]
def bubble_sort(self
):
"""冒泡排序"""
for i
in range(len(self
.li
) - 1):
for j
in range(len(self
.li
) - 1 - i
):
self
.campare_elem
(j
, j
+ 1)
return self
.li
if __name__
== "__main__":
li
= [9, 0, 1, 6, 5, 2, 12, 10, 8, 21, 7]
bubble
= BubbleSort
(li
)
print(bubble
.bubble_sort
())
转载请注明原文地址:https://tech.qufami.com/read-125.html