python---希尔排序

我觉得,使用哪种排序,还是要看要排序的数据规模。

当数据规模较小时,怎么方便怎么来。

而一旦数据量大了,也要根据数据本身的一些特点,来选择合适的排序算法,

然后,测试几把时间复杂度和空间复杂度,再作最终决定。

 

# 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

  

转载于:https://www.cnblogs.com/aguncn/p/10689253.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值