冒泡排序——Python实现

wordmhg 2019-10-28

冒泡排序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}秒")

相关推荐