本文所有代码,都在jupyter notebook 上做过验证。大家也可以放在自己的代码里单独调用。
算法复杂性分析
冒泡法:
相邻的两个数进行比较后根据大小需求交换位置。
大O表示是 O()
冒泡法实现过程简单,但效率较低,适用于数据量较小的的排序任务。
def counting_sort(arr):
"""
Counting_sort
Sorting a array which has no element greater than k
Creating a new temp_arr,where temp_arr[i] contain the number of
element less than or equal to i in the arr
Then placing the number i into a correct position in the result_arr
return the result_arr
Complexity: 0(n)
"""
m = min(arr)
# in case there are negative elements, change the array to all positive element
different = 0
if m < 0:
# save the change, so that we can convert the array back to all positive number
different = -m
for i in range(len(arr)):
arr[i] += -m
k = max(arr)
temp_arr = [0] * (k + 1) #temp_arr[i]表示元素i出现的次数,如果有多次,通过循环重复追加
for i in range(0, len(arr)):
temp_arr[arr[i]] = temp_arr[arr[i]] + 1
# temp_array[i] contain the times the number i appear in arr
for i in range(1, k + 1):
temp_arr[i] = temp_arr[i] + temp_arr[i - 1]
# temp_array[i] contain the number of element less than or equal i in arr
result_arr = arr.copy()
# creating a result_arr an put the element in a correct positon
for i in range(len(arr) - 1, -1, -1): #result_arr 按正确位置存放,返回 result_arr
result_arr[temp_arr[arr[i]] - 1] = arr[i] - different
temp_arr[arr[i]] = temp_arr[arr[i]] - 1
return result_arr
桶排序:
工作的原理是将数组分到有限数量的桶子里。每个桶子再个别排序。
桶排序的平均时间复杂度为线性的O(N),桶数量M越大,其效率越高,如果输入数据非常庞大,而桶的数量也非常多,则空间代价无疑是非常大。桶排序是稳定的。
def bucket_sort(arr):
''' Bucket Sort
Complexity: O(n^2)
The complexity is dominated by nextSort
'''
# The number of buckets and make buckets
num_buckets = len(arr)
buckets = [[] for bucket in range(num_buckets)] #创建桶
# Assign values into bucket_sort
for value in arr:
index = value * num_buckets // (max(arr) + 1)
buckets[index].append(value) #先进行赋值,准备排序
# Sort
sorted_list = [] #输出列表
for i in range(num_buckets):
sorted_list.extend(next_sort(buckets[i])) #依次进输出列表,完成排序
return sorted_list
def next_sort(arr): #插入排序
# We will use insertion sort here.
for i in range(1, len(arr)):
j = i - 1
key = arr[i]
while arr[j] > key and j >= 0:
arr[j+1] = arr[j]
j = j - 1
arr[j + 1] = key
return arr