python冒泡排序

参考:www.bilibili.com/video/BV1E4…

python实现

import datetime
import random
from functools import wraps

tempList = [random.randint(0, 100000) for x in range(50000)]


def logger(function):
    @wraps(function)
    def wrapper(*args, **kwargs):
        start = datetime.datetime.now().timestamp()
        result = function(*args, **kwargs)
        end = datetime.datetime.now().timestamp()
        print(f"总共花了{int(end - start)}s")
        return result

    return wrapper


@logger
def bubbleSort(l: list) -> list:
    flag = False
    for i in range(len(l) - 1):
        for j in range(0, len(l) - 1 - i):
            if l[j] > l[j + 1]:
                flag = True
                l[j], l[j + 1] = l[j + 1], l[j]
        # flag为False,说明没有发生排序,直接break
        if not flag:
            break
        else:
            flag = False
    return l


@logger
def bubbleSort2(l: list) -> list:
    flag = False
    for i in range(len(l) - 1):
        for j in range(len(l) - 1, i, -1):
            if l[j] < l[j - 1]:
                flag = True
                l[j], l[j - 1] = l[j - 1], l[j]
        # flag为False,说明没有发生排序,直接break
        if not flag:
            break
        else:
            flag = False
    return l


bubbleSort(tempList)
# bubbleSort2(tempList)
  • 我是真没想到冒泡50000个元素花了127s...

image.png

  • 然后用go实现了下,3s...
func main() {
	exchange := false
	rand.Seed(time.Now().UnixNano())
	var l = [50000]int{}
	for i := 0; i < 50000; i++ {
		l[i] = rand.Intn(50000)
	}
	start := time.Now().Unix()
	for i := 0; i < len(l)-1; i++ {
		for j := 0; j < len(l)-1-i; j++ {
			if l[j] > l[j+1] {
				exchange = true
				temp := l[j+1]
				l[j+1] = l[j]
				l[j] = temp
			}
		}
		if !exchange {
			break
		} else {
			exchange = false
		}
	}
	end := time.Now().Unix()
	print("排序花了",end - start,"秒")
}

image.png