计数排序、基数排序及桶排序
计数排序思想:
对每一个元素,确定小于其的元素个数,利用这一信息即可将其放入正确的位置。
计数排序时间复杂度:Θ(n)
计数排序示例:
from random import randint def counting_sort(a,b,max_number):
#用于记录各元素出现次数 c = [] for i in range(max_number+1): c.append(0) for number in a: c[number] += 1 for i in range(1,max_number+1): c[i] += c[i-1] for number in a[::-1]: b[c[number]-1] = number c[number] -= 1 return b def main(args): a = [] b = [] for i in range(100): a.append(randint(0,100)) b.append(0) print(a) print(counting_sort(a,b,max(a))) return 0 if __name__ == '__main__': import sys sys.exit(main(sys.argv))
基数排序思想:
对欲排序数组按最低有效位(即数字的最后一位)进行排序,之后,用同样的方法对次低有效位进行排序,重复该过程直至所有位数都已排好序。
基数排序时间复杂度:Θ(n)
示例代码:
from random import randint import copy def counting_sort(a,max_number): c = [] b = [] for i in range(len(a)): b.append(a[i]) for i in range(max_number+1): c.append(0) for numbers in a: c[numbers.b] += 1 for i in range(1,max_number+1): c[i] += c[i-1]
#利用某一位数进行排序 for numbers in a[::-1]: b[c[numbers.b]-1] = numbers c[numbers.b] -= 1 return b def radix_sort(a,d): c = [] for i in range(len(a)): c.append(Numbers(a[i],0)) for index in range(1,d+1): b = [] for i in range(len(a)):
#得到某一位数的值 b.append((c[i].a % (10 ** index))//(10 ** (index - 1))) c[i].b = b[i] c = counting_sort(c,9) for i in range(len(a)): a[i] = c[i].a
#用于储存每个数的值与其某一位数的值 class Numbers(): def __init__(self,a,b): self.a = a self.b = b def main(args): a = [] for i in range(10): a.append(randint(0,10000)) print(a) radix_sort(a,4) print(a) return 0 if __name__ == '__main__': import sys sys.exit(main(sys.argv))
桶排序思想:
将[0,1)区间划分为n个大小相同的子区间,然后将欲排序数组分别放到各个桶中。之后对每个桶进行排序。
桶排序的期望时间复杂度:Θ(n)
示例代码:
from random import random from random import randint def quick_sort(a,i,j): if i < j: q = randomized_partition(a,i,j) quick_sort(a,i,q-1) quick_sort(a,q+1,j) def randomized_partition(a,i,j): ret = i - 1 int_random = randint(i,j) tmp = a[j] a[j] = a[int_random] a[int_random] = a[j] for k in range(j-i): if a[i+k] < a[j]: ret += 1 tmp = a[i+k] a[i+k] = a[ret] a[ret] = tmp ret += 1 tmp = a[j] a[j] = a[ret] a[ret] = tmp return ret def bucket_sort(a):
#b为列表,储存各个区间的值 b = [] for i in range(len(a)): tmp = [] b.append(tmp) for number in a: b[int((len(a)-1) * number)].append(number)
#划分完毕后利用快排对每个桶进行排序 for list_b in b: quick_sort(list_b,0,len(list_b)-1) i = 0 for list_b in b: for number in list_b: a[i] = number i += 1 def main(args): a = [] for i in range(100): a.append(round(random(),2)) print(a) bucket_sort(a) print(a) return 0 if __name__ == '__main__': import sys sys.exit(main(sys.argv))