鸡尾酒排序

鸡尾酒排序的流程

先对数组从左到右进行升序的冒泡排序;
再对数组进行从右到左的降序的冒泡排序;
以此类推,持续的、依次的改变冒泡的方向,并不断缩小没有排序的数组范围;

一个动图(来自hujingshuang):


cocktail

python实现

def cocktail_sort(seq):
    length = len(seq)
    i = 0
    while i < length:
        right = length -1 # 取最后一个数的索引值
        while right > i:  # 从右向左找最小值
            if seq[right-1]>seq[right]:
                seq[right-1],seq[right]=seq[right],seq[right-1]
            right -= 1

        i += 1
        left = i  # 找到最小后从下一个位置开始从向右找最大值
        while left < length-1:
            if seq[left]>seq[left+1]:
                seq[left],seq[left+1]=seq[left+1],seq[left]
            left += 1

        length -= 1 #找到最大值后从前一位开始向左找最小值


seq = [2,8,7,6,4,3,5]
cocktail_sort(seq)

执行过程:https://goo.gl/9ye7Wq

时间复杂度

时间复杂度 O(n2)
最优时间复杂度 O(n)
平均时间复杂度 O(n2)


参考:
https://blog.csdn.net/hujingshuang/article/details/48741207
https://blog.csdn.net/David_Dai_1108/article/details/67690405

posted @ 2018-08-20 22:48  Siucaan  阅读(176)  评论(0编辑  收藏  举报