📜  鸡尾酒排序的Python程序

📅  最后修改于: 2022-05-13 01:56:56.281000             🧑  作者: Mango

鸡尾酒排序的Python程序

鸡尾酒排序是冒泡排序的一种变体。冒泡排序算法总是从左边遍历元素,并在第一次迭代中将最大元素移动到正确的位置,在第二次迭代中将最大元素移动到第二大元素,依此类推。鸡尾酒排序交替地在两个方向上遍历给定的数组。


算法:

算法的每次迭代分为 2 个阶段:

  1. 第一阶段从左到右循环遍历数组,就像冒泡排序一样。在循环期间,比较相邻的项目,如果左侧的值大于右侧的值,则交换值。在第一次迭代结束时,最大的数字将驻留在数组的末尾。
  2. 第二阶段以相反的方向循环遍历数组——从最近排序项之前的项开始,然后返回到数组的开头。在这里,相邻的项目也会进行比较,并在需要时进行交换。
# Python program for implementation of Cocktail Sort
  
def cocktailSort(a):
    n = len(a)
    swapped = True
    start = 0
    end = n-1
    while (swapped==True):
  
        # reset the swapped flag on entering the loop,
        # because it might be true from a previous
        # iteration.
        swapped = False
  
        # loop from left to right same as the bubble
        # sort
        for i in range (start, end):
            if (a[i] > a[i+1]) :
                a[i], a[i+1]= a[i+1], a[i]
                swapped=True
  
        # if nothing moved, then array is sorted.
        if (swapped==False):
            break
  
        # otherwise, reset the swapped flag so that it
        # can be used in the next stage
        swapped = False
  
        # move the end point back by one, because
        # item at the end is in its rightful spot
        end = end-1
  
        # from right to left, doing the same
        # comparison as in the previous stage
        for i in range(end-1, start-1,-1):
            if (a[i] > a[i+1]):
                a[i], a[i+1] = a[i+1], a[i]
                swapped = True
  
        # increase the starting point, because
        # the last stage would have moved the next
        # smallest number to its rightful spot.
        start = start+1
  
# Driver code to test above
a = [5, 1, 4, 2, 8, 0, 2]
cocktailSort(a)
print("Sorted array is:")
for i in range(len(a)):
    print ("%d" %a[i]),

输出:

Sorted array is:
0 1 2 2 4 5 8

请参阅完整的鸡尾酒排序文章了解更多详情!