冒泡排序——Python实现
冒泡排序Python实现
# -*- coding: utf-8 -*-
# @Time : 2019/10/28 19:41
# @Author : yuzhou_1shu
# @Email :
# @File : bubble_sort.py
# @Software: PyCharm
def bubble_sort(collection):
# 求序列的长度
length = len(collection)
# 从序列中第一个元素开始以此跟后一个比较
for i in range(length - 1):
swapped = False
for j in range(length - i - 1):
if collection[j] > collection[j+1]:
collection[j], collection[j+1] = collection[j+1], collection[j]
swapped = True
if not swapped:
break # 如果已经排序好了,退出循环
return collection
if __name__ == "__main__":
import time
user_input = input("请输入数字,并以英文逗号隔开: ").strip()
unsorted = [int(item) for item in user_input.split(",")]
start_time = time.process_time()
print("排序后:", *bubble_sort(unsorted), sep=",")
print(f"排序消耗时间: {time.process_time() - start_time}秒") 相关推荐
小海 2020-06-25
elizabethxxy 2020-11-06
pythonxuexi 2020-10-30
retacnyue 2020-09-28
pythonxuexi 2020-09-06
Morelia 2020-09-04
zhaobig 2020-08-17
linkequa 2020-08-16
CloudXli 2020-08-14
kikaylee 2020-08-12
LowisLucifer 2020-08-09
xiesheng 2020-08-06
Tristahong 2020-08-05
CatherineC00 2020-08-01
Andrewjdw 2020-07-26
reallyr 2020-07-18
wordmhg 2020-07-16
yawei 2020-07-06