冒泡排序及其二次优化

参考网址

了解前置知识

https://www.cnblogs.com/king-ding/p/bubblesort.html

优化一:_opsort()

某轮冒泡过程中没有发生元素交换,则说明整个序列已经排好序,此时不需要再进行后续的冒泡操作,可以直接结束程序。

for i in range(self.len_datas-1):
            flag = True
            for j in range(self.len_datas-1-i):
                if(self.datas[j]>self.datas[j+1]):
                    self.datas[j], self.datas[j+1] = self.datas[j+1], self.datas[j]
                    flag = False
            if flag:
                break

优化二:_opersort()

假设有100个元素的数组,仅前面10个无序,后面90个都已排好序且都大于前面10个元素,那么在第一轮冒泡过程后,最后发生交换的位置必定小于10,且该位置之后的元素必定已经有序。只需记录该位置,第二次从数组头部遍历到这个位置即可

#记录位置tag
for j in range(self.len_datas-1):
            if(self.datas[j]>self.datas[j+1]):
                self.datas[j], self.datas[j+1] = self.datas[j+1], self.datas[j]
                tag = j+1
                #print(tag)

规范代码

class BubbleSort(object):
    '''
    self.datas:数据列表
    self.len_datas:数据长度
    _sort():排序函数
    _opsort():优化后的排序函数
    _opersort():再优化后的排序函数
    show():输出序列
    
    用法:
    BubbleSort(datas):实例化对象
    BubbleSort(datas)._sort():排序
    BubbleSort(datas).show():输出结果
    '''
    
    def __init__(self,datas):
        self.datas = datas
        self.len_datas = len(datas)
        
    def _sort(self):
        for i in range(self.len_datas-1):
            for j in range(self.len_datas-1-i):
                if(self.datas[j]>self.datas[j+1]):
                    self.datas[j], self.datas[j+1] = self.datas[j+1], self.datas[j]
     
    def _opsort(self):
        for i in range(self.len_datas-1):
            flag = True
            for j in range(self.len_datas-1-i):
                if(self.datas[j]>self.datas[j+1]):
                    self.datas[j], self.datas[j+1] = self.datas[j+1], self.datas[j]
                    flag = False
            if flag:
                break
                
    def _opersort(self):
        for j in range(self.len_datas-1):
            if(self.datas[j]>self.datas[j+1]):
                self.datas[j], self.datas[j+1] = self.datas[j+1], self.datas[j]
                tag = j+1
                #print(tag)
                    
            for i in range(tag):
                flag = True
                for j in range(tag-1-i):
                    if(self.datas[j]>self.datas[j+1]):
                        self.datas[j], self.datas[j+1] = self.datas[j+1], self.datas[j]
                        flag = False
                    
                if flag:
                    break
            
    def show(self):
        print("Result:")
        for i in self.datas:
            print(i,end=',')
    
if __name__ == '__main__':
    try:
        #输入整数列表(英文','):1,5,6,9,8
        datas = input("input some integers;split with ','")
        datas = datas.split(',')
        datas = [int(datas[i]) for i in range(len(datas))]
    except Exception:
        pass
    
    bls = BubbleSort(datas)
    #bls._opsort()
    #bls._sort()
    bls._opersort()
    bls.show()
    

#参考网址:https://www.cnblogs.com/king-ding/p/bubblesort.html
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
冒泡排序是一种简单的排序算法,它重复地遍历要排序的列表,比较相邻的元素,并按照大小顺序交换它们,直到整个列表排序完成。冒泡排序的基本思想是每次将最大的元素“冒泡”到列表的末尾。 选择排序也是一种简单的排序算法,它每次从未排序的部分中选择最小的元素,并将其放在已排序部分的末尾。选择排序的基本思想是每次选择最小的元素放在已排序部分的末尾。 冒泡排序和选择排序都是基于比较的排序算法,它们的时间复杂度都是O(n^2)。然而,冒泡排序和选择排序在最坏情况下的性能相对较差,因为它们需要进行大量的比较和交换操作。 为了优化冒泡排序,可以引入一个标志位来记录每一轮是否发生了交换。如果某一轮没有发生交换,说明列表已经有序,可以提前结束排序。这样可以减少不必要的比较和交换操作,提高排序的效率。 以下是冒泡排序和选择排序的示例代码: 冒泡排序: ```python def bubble_sort(arr): n = len(arr) for i in range(n-1): flag = False for j in range(n-i-1): if arr[j] > arr[j+1]: arr[j], arr[j+1] = arr[j+1], arr[j] flag = True if not flag: break return arr # 示例 arr = [64, 34, 25, 12, 22, 11, 90] sorted_arr = bubble_sort(arr) print("Sorted array:", sorted_arr) # 输出:[11, 12, 22, 25, 34, 64, 90] ``` 选择排序: ```python def selection_sort(arr): n = len(arr) for i in range(n-1): min_idx = i for j in range(i+1, n): if arr[j] < arr[min_idx]: min_idx = j arr[i], arr[min_idx] = arr[min_idx], arr[i] return arr # 示例 arr = [64, 34, 25, 12, 22, 11, 90] sorted_arr = selection_sort(arr) print("Sorted array:", sorted_arr) # 输出:[11, 12, 22, 25, 34, 64, 90] ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值