计数排序
之前的排序算法无论是冒泡排序还是快速排序等,都是基于元素之间的比较来排序的,而在特殊的情况下,计数排序算法利用数组下标来确定元素的正确位置。
#找到数组中的最大值和最小值
def findMinMax(array):
maxnumber = array[0]
for i in range(1,len(array)):
if array[i]>maxnumber:
maxnumber = array[i]
minnumber = array[0]
for i in range(1,len(array)):
if array[i]<minnumber:
minnumber = array[i]
return maxnumber,minnumber
def makearray(maxnumber,minnumber,array):
arraylength = maxnumber-minnumber+1
newarray= arraylength*[0]
for i in range(len(array)):
newarray[array[i] - minnumber] += 1
sum=0
for i in range(len(newarray)):
sum+=newarray[i]
newarray[i]=sum
return newarray
def sort(array,newarray,minnumber):
sortarray=len(array)*[0]
for i in range(len(array)-1,-1,-1):
sortarray[newarray[array[i]-minnumber]-1]=array[i]
newarray[array[i]-minnumber]-=1
return sortarray
list=[95,94,91,98,99,90,99,93,91,92]
a,b = findMinMax(list)
array = makearray(a,b,list)
print(array)
newarray = sort(list,array,b)
print(newarray)
# 计数排序的注意点
# 1 当数列最大值最小值差距过大时,并不适用计数排序
# 2 当数列元素不是整数,并不适用计数排序
桶排序:希望桶中元素分布尽可能是均匀的,不然可能会白白创建很多空桶。
#找到数组中的最大值和最小值
array=[4.12,6.421,0.0023,3.0,2.123,8.122,4.12,10.09]
maxnumber = array[0]
for i in range(1,len(array)):
if array[i]>maxnumber:
maxnumber = array[i]
minnumber = array[0]
for i in range(1,len(array)):
if array[i]<minnumber:
minnumber = array[i]
d = maxnumber-minnumber
bucketNum =len(array)
bucket = [[] for _ in range(bucketNum)]
print(bucket)
for data in array:
index = int((data-minnumber)*(bucketNum-1)/d)
bucket[index].append(data)
print(bucket)
for i in range(bucketNum):
if bucket[i]!=[]:
bucket[i].sort()
index=0
sortarray=len(array)*[0]
for i in range(bucketNum):
if bucket[i] != []:
for j in range(len(bucket[i])):
sortarray[index]=bucket[i][j]
index+=1
print(sortarray)
算法复杂度分析:
假设数组长度为n,桶个数为m.
1 求数组最大值最小值,运算量为n.
2 创建桶,运算量为m。
3遍历数组,将其放到对应的桶中,运算量为n;
4 对每个桶内元素进行排序,假设平均每个桶内元素为n/m,那么运算量为n/m*log(n/m)*m
5输出有序数组,运算量为n.
sum = 3n+m+n(logn-logm).