计数、基数和桶排序的Python实现

计数排序:

#! /usr/bin/env python
#coding=utf-8

import random,copy
from collections import defaultdict

def count_sort(lst, key=lambda x: x):
    B,C = [], defaultdict(list)
    for x in lst:
        C[key(x)].append(x)
    for k in range(min(C),max(C)+1):
        B.extend(C[k])
    return B

def count_sort2(lst):
    # sort integers only
    B, C = lst[:], defaultdict(int)
    for x in lst:
        C[x] += 1
    for k in range(min(C)+1,max(C)+1):
        C[k] = C[k] + C[k-1]
    for i in range(len(lst)-1,-1,-1):
        B[C[lst[i]]-1] = lst[i]
        C[lst[i]] = C[lst[i]] - 1
    return B
   
    

if  __name__ =='__main__':
    lst = [random.randrange(20) for i in range(10)]
    lst2 = copy.deepcopy(lst)
    print(lst)
    lst2.sort()
    print(lst2)
    
    lst = count_sort2(lst)
    print(lst)
    
    

基数排序:

#! /usr/bin/env python
#coding=utf-8

import random,copy

def radix_sort(lst,d):
    print("radix sorting...")
    for x in range(d):
        slots = [[] for _ in range(10)]
        for k in lst:
            slots[k/(10**x)%10].append(k)
        lst = [a for b in slots for a in b]
        print(lst)
    print("...sorting over!")
    return lst

if  __name__ =='__main__':
    lst = [random.randrange(1000) for i in range(10)]
    lst2 = lst[:]
    lst2.sort()
    print(lst)
    print(lst2)
    
    lst = radix_sort(lst,3)
    print(lst)
    
    

桶排序:

#! /usr/bin/env python
#coding=utf-8

import random,copy

def insert_sort(lst):
    for i in range(1,len(lst)):
        cur_value = lst[i]
        while i > 0 and lst[i-1] > cur_value:
            lst[i] = lst[i-1]
            i = i - 1
        lst[i] = cur_value

def bucket_sort_helper(lst,n):
    # n --> bucket nums
    buckets = [[] for _ in range(n)]
    for x in lst:
        buckets[int(n*x)].append(x)
    B = []
    for bucket in buckets:
        insert_sort(bucket)
        B.extend(bucket)
    return B

def bucket_sort(lst):
    return bucket_sort_helper(lst,10)

    
if  __name__ == '__main__':
    lst = [int(random.random()*100)/100.0 for i in range(10)]
    lst2 = lst[:]
    lst2 = sorted(lst2)
    print(lst)
    print(lst2)
    
    lst = bucket_sort(lst)
    print(lst)
    



你可能感兴趣的:(排序,算法,Python)