Skip to content

Commit 65f6a62

Browse files
committed
下沉迭代+基数排序
1 parent 0179256 commit 65f6a62

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

Sorting/SortingAL.py

+48
Original file line numberDiff line numberDiff line change
@@ -210,6 +210,8 @@ def counting_sort(self, lst):
210210

211211
return res
212212

213+
# 递归版sift_down
214+
213215
def __sift_down(self, lst, st, ed):
214216
"""
215217
:堆排序下沉函数,时间复杂度O(lgn)
@@ -226,13 +228,59 @@ def __sift_down(self, lst, st, ed):
226228
lst[st], lst[lar] = lst[lar], lst[st]
227229
self.__sift_down(lst, lar, ed)
228230

231+
# 迭代版sift_down
232+
233+
# def __sift_down(self, lst, st, ed):
234+
# while st <= (ed + 1) / 2 - 1:
235+
# if 2 * st + 2 <= ed:
236+
# lar = 0
237+
# if lst[st * 2 + 1] > lst[st * 2 + 2]:
238+
# lar = st * 2 + 1
239+
# else:
240+
# lar = st * 2 + 2
241+
# if lst[lar] > lst[st]:
242+
# lst[lar], lst[st] = lst[st], lst[lar]
243+
# st = lar
244+
# else:
245+
# break
246+
# elif lst[2 * st + 1] > lst[st]:
247+
# lst[2 * st + 1], lst[st] = lst[st], lst[st * 2 + 1]
248+
# st = st * 2 + 1
249+
# else:
250+
# break
251+
229252
def __build_max_heap(self, lst):
230253
for s in xrange(len(lst) / 2 - 1, -1, -1):
231254
self.__sift_down(lst, s, len(lst) - 1)
232255

233256
def heap_sort(self, lst, n):
257+
"""
258+
:堆排序主函数, 时间复杂度O(n)
259+
:type lst: List
260+
:type n: int
261+
:堆排序有没有可能写出迭代的sift_down函数?
262+
"""
234263
self.__build_max_heap(lst)
235264
for s in xrange(n):
236265
lst[0], lst[n - s - 1] = lst[n - s - 1], lst[0]
237266
self.__sift_down(lst, 0, n - s - 2)
238267
return lst
268+
269+
def radix_sort(self, lst, number_of_bits):
270+
"""
271+
:基数排序,时间复杂度O(kn),k为最大数的位数
272+
:type lst: List
273+
:type number_of_bits: int
274+
"""
275+
binArray = [[] for _ in xrange(10)]
276+
col = 1
277+
for s in xrange(number_of_bits):
278+
for a in lst:
279+
index = (a / col) % 10
280+
binArray[index].append(a)
281+
lst = []
282+
for array in binArray:
283+
while len(array) != 0:
284+
lst.append(array.pop(0))
285+
col *= 10
286+
return lst

0 commit comments

Comments
 (0)