我觉得,使用哪种排序,还是要看要排序的数据规模。
当数据规模较小时,怎么方便怎么来。
而一旦数据量大了,也要根据数据本身的一些特点,来选择合适的排序算法,
然后,测试几把时间复杂度和空间复杂度,再作最终决定。
# coding = utf-8
# ========希尔排序========
def shell_sort(a_list):
loop_count = 0
sublist_count = len(a_list) // 2
while sublist_count > 0:
loop_count += 1
for start_pos in range(sublist_count):
loop_count += 1
# 在每个子列表上应用了插入排序
gap_insert_sort(a_list, start_pos, sublist_count)
print('After increments of size ', sublist_count, 'The list is ', a_list)
sublist_count //= 2
print('======== shell_sort loop_count========', loop_count)
# 插入排序
def gap_insert_sort(a_list, start, gap):
loop_count = 0
for index in range(start+gap, len(a_list), gap):
loop_count += 1
current_value = a_list[index]
pos = index
while pos >= gap and a_list[pos-gap] > current_value:
loop_count += 1
a_list[pos] = a_list[pos-gap]
pos = pos - gap
a_list[pos] = current_value
print('======== gap_insert_sort loop_count========', loop_count)
my_list = [4, 5, 7, 2, 9, 7, 9, 54, 765, 45, 9876, 34, 12343, 36]
shell_sort(my_list)
print(my_list)
D:\cheng\test\Scripts\python.exe D:/GIT/Prism4K/Prism4K/document/tests.py ======== gap_insert_sort loop_count======== 1 ======== gap_insert_sort loop_count======== 1 ======== gap_insert_sort loop_count======== 1 ======== gap_insert_sort loop_count======== 1 ======== gap_insert_sort loop_count======== 1 ======== gap_insert_sort loop_count======== 1 ======== gap_insert_sort loop_count======== 1 After increments of size 7 The list is [4, 5, 7, 2, 9, 7, 9, 54, 765, 45, 9876, 34, 12343, 36] ======== gap_insert_sort loop_count======== 5 ======== gap_insert_sort loop_count======== 6 ======== gap_insert_sort loop_count======== 4 After increments of size 3 The list is [2, 5, 7, 4, 9, 7, 9, 36, 34, 45, 54, 765, 12343, 9876] ======== gap_insert_sort loop_count======== 18 After increments of size 1 The list is [2, 4, 5, 7, 7, 9, 9, 34, 36, 45, 54, 765, 9876, 12343] ======== shell_sort loop_count======== 14 [2, 4, 5, 7, 7, 9, 9, 34, 36, 45, 54, 765, 9876, 12343] Process finished with exit code 0