#!/usr/bin/env python # -*- coding: utf-8 -*-import randomimport time def cal_time(func): def inner(*args, **kwargs): start = time.time() res = func(*args, **kwargs) end = time.time() print("%s用时为%s" % (func.__name__, end - start)) return res return inner
冒泡排序
@cal_time def bubble_sort(li): for i in range(len(li) - 1): flag = False for j in range(len(li) - 1 - i): if li[j] > li[j + 1]: li[j], li[j + 1] = li[j + 1], li[j] flag = True if not flag: return li return li
选择排序
@cal_time def select_sort(li): for i in range(len(li) - 1): mindoc = i for j in range(i + 1, len(li)): if li[mindoc] > li[j]: li[mindoc], li[j] = li[j], li[mindoc] return li
快速排序
def patition(li, left, right): tmp = li[left] while left < right: while left < right and tmp <= li[right]: right -= 1 li[left] = li[right] while left < right and tmp >= li[left]: left += 1 li[right] = li[left] li[left] = tmp return left def quick_sort(li, left, right): if left < right: mid = patition(li, left, right) quick_sort(li, left, mid - 1) quick_sort(li, mid + 1, right) @cal_time def quick(li, left, right): quick_sort(li, left, right)
if __name__ == ‘__main__‘: # 冒泡排序 li = [random.randint(1, 1000) for i in range(1000)] # res = bubble_sort(li) # print(res) # 选择排序 # res=select_sort(li) # print(res) # 快速排序 quick(li, 0, len(li) - 1)
原文地址:https://www.cnblogs.com/ouyang99-/p/10489098.html
时间: 2024-11-05 06:29:02