defcountSort(nums): ''' Sort non-negative intergers. O(N+K) time complexity O(N+K) space complexity ''' k = max(nums) c = [0] * (k+1) sortedArray = [0] * len(nums) # Place for n in nums: c[n] += 1 # Count for ind, val in enumerate(c[:-1]): c[ind+1] += c[ind] # Sort for n in nums: sortedArray[c[n]-1] = n return sortedArray
defbucketSort(nums): ''' Sort non-negative intergers. O(N) time complexity ''' bucketNum = 2000 k = max(nums) # The upper bound. # Initializing all the buckets buckets = [[] for i in xrange(bucketNum)]
# Map to buckets for n in nums: buckets[n/k*(bucketNum-1)].append(n) # Sort each bucket. O(N/M*log(N/M)) time consumption each buckets = [sorted(bucket) for bucket in buckets] # Merge from itertools import chain return list(chain(*buckets))
基数排序
最后呢就是基数排序,其实只是为了可以按照多个关键字进行排序而设计的一种方法,在这里对于整数情况,我们直接按每位拆开,由地位至高位一次排序即可,每一次小的排序过程我们都使用了稳定的桶排序。时间复杂度实际是 k * O(N),代码如下:
桶排序
1 2 3 4 5 6 7 8 9 10 11 12 13
defradixSort(nums): radix = 10 import math # Maxium digits k = int(math.ceil(math.log(max(nums), radix))) sortedNums = nums for i in range(k): buckets = [[] for j in range(radix)] for num in sortedNums: buckets[num / (radix**(i+1)) % radix].append(num) from itertools import chain sortedNums = list(chain(*buckets)) return sortedNums