Bucket Sort. Θ(n) averagely

from random import choices
from math import ceil

scope = 10
amount = 100
numOfBuckets = ceil(amount / scope)
source = choices(range(amount), k=amount)
buckets = [[] for _ in range(numOfBuckets)]

for x in source:
    buckets[x//scope].append(x)

# Insertion sort
for arr in buckets:
    lenOfArr = len(arr)
    if lenOfArr < 2:
        break
    for i in range(1, lenOfArr):
        comp = arr[i]
        pos = 0
        for j in range(i-1, -1, -1):
            if arr[j] > comp:
                arr[j+1] = arr[j]
            else:
                pos = j + 1
                break
        arr[pos] = comp

dest = []
for x in buckets:
    dest += x

你可能感兴趣的:(Bucket Sort. Θ(n) averagely)