📜  鸡尾酒排序

📅  最后修改于: 2021-04-23 18:11:59             🧑  作者: Mango

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

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

  1. 第一级从左到右循环遍历数组,就像冒泡排序一样。在循环期间,将比较相邻的项目,如果左侧的值大于右侧的值,则将交换值。在第一次迭代结束时,最大数量将驻留在数组的末尾。
  2. 第二阶段以相反的方向循环通过数组-从刚排序的项目之前的项目开始,然后移回数组的开头。同样,在这里,比较相邻的项目,并在需要时进行交换。

例子 :

让我们考虑一个示例数组(5 1 4 2 8 0 2)

第一次前进通行证:
( 5 1 4 2 8 0 2)? ( 1 5 4 2 8 0 2),交换自5> 1
(1 5 4 2 8 0 2)? (1 4 5 2 8 0 2),交换自5> 4
(1 4 5 2 8 0 2)? (1 4 2 5 8 0 2),从5> 2开始交换
(1 4 2 5 8 0 2)? (1 4 2 5 8 0 2)
(1 4 2 5 8 0 2)? (1 4 2 5 0 8 2),从8> 0交换
(1 4 2 5 0 8 2 )? (1 4 2 5 0 2 8 ),交换自8> 2
第一次向前通过之后,数组的最大元素将出现在数组的最后一个索引处。
第一次后退通行证:
(1 4 2 5 0 2 8)? (1 4 2 5 0 2 8)
(1 4 2 5 0 2 8)? (1 4 2 0 5 2 8),从5> 0交换
(1 4 2 0 5 2 8)? (1 4 0 2 5 2 8),交换自2> 0
(1 4 0 2 5 2 8)? (1 0 4 2 5 2 8),交换自4> 0
( 1 0 4 2 5 2 8)? ( 0 1 4 2 5 2 8),从1> 0交换
在第一次向后传递之后,数组的最小元素将出现在数组的第一个索引处。
第二次前进通行证:
(0 1 4 2 5 2 8) (0 1 4 2 5 2 8)
(0 1 4 2 5 2 8) (0 1 2 4 5 2 8),交换自4> 2
(0 1 2 4 5 2 8) (0 1 2 4 5 2 8)
(0 1 2 4 5 2 8) (0 1 2 4 2 5 8),交换自5> 2
第二次倒退通行证:
(0 1 2 4 2 5 8) (0 1 2 2 4 5 8),交换自4> 2
现在,该数组已经排序,但是我们的算法不知道它是否完成。该算法需要完成整个过程,而无需进行任何交换即可知道它已被排序。
(0 1 2 2 4 5 8) (0 1 2 2 4 5 8)
(0 1 2 2 4 5 8) (0 1 2 2 4 5 8)
下面是上述算法的实现:

C++
// C++ implementation of Cocktail Sort
#include 
using namespace std;
 
// Sorts arrar a[0..n-1] using Cocktail sort
void CocktailSort(int a[], int n)
{
    bool swapped = true;
    int start = 0;
    int end = n - 1;
 
    while (swapped)
    {
        // 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 (int i = start; i < end; ++i)
        {
            if (a[i] > a[i + 1]) {
                swap(a[i], a[i + 1]);
                swapped = true;
            }
        }
 
        // if nothing moved, then array is sorted.
        if (!swapped)
            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;
 
        // from right to left, doing the
        // same comparison as in the previous stage
        for (int i = end - 1; i >= start; --i)
        {
            if (a[i] > a[i + 1]) {
                swap(a[i], a[i + 1]);
                swapped = true;
            }
        }
 
        // increase the starting point, because
        // the last stage would have moved the next
        // smallest number to its rightful spot.
        ++start;
    }
}
 
/* Prints the array */
void printArray(int a[], int n)
{
    for (int i = 0; i < n; i++)
        printf("%d ", a[i]);
    printf("\n");
}
 
// Driver code
int main()
{
    int a[] = { 5, 1, 4, 2, 8, 0, 2 };
    int n = sizeof(a) / sizeof(a[0]);
    CocktailSort(a, n);
    printf("Sorted array :\n");
    printArray(a, n);
    return 0;
}


Java
// Java program for implementation of Cocktail Sort
public class CocktailSort
{
    void cocktailSort(int a[])
    {
        boolean swapped = true;
        int start = 0;
        int end = a.length;
 
        while (swapped == true)
        {
            // reset the swapped flag on entering the
            // loop, because it might be true from a
            // previous iteration.
            swapped = false;
 
            // loop from bottom to top same as
            // the bubble sort
            for (int i = start; i < end - 1; ++i)
            {
                if (a[i] > a[i + 1]) {
                    int temp = a[i];
                    a[i] = a[i + 1];
                    a[i + 1] = temp;
                    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 top to bottom, doing the
            // same comparison as in the previous stage
            for (int i = end - 1; i >= start; i--)
            {
                if (a[i] > a[i + 1])
                {
                    int temp = a[i];
                    a[i] = a[i + 1];
                    a[i + 1] = temp;
                    swapped = true;
                }
            }
 
            // increase the starting point, because
            // the last stage would have moved the next
            // smallest number to its rightful spot.
            start = start + 1;
        }
    }
 
    /* Prints the array */
    void printArray(int a[])
    {
        int n = a.length;
        for (int i = 0; i < n; i++)
            System.out.print(a[i] + " ");
        System.out.println();
    }
 
    // Driver code
    public static void main(String[] args)
    {
        CocktailSort ob = new CocktailSort();
        int a[] = { 5, 1, 4, 2, 8, 0, 2 };
        ob.cocktailSort(a);
        System.out.println("Sorted array");
        ob.printArray(a);
    }
}


Python
# 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
a = [5, 1, 4, 2, 8, 0, 2]
cocktailSort(a)
print("Sorted array is:")
for i in range(len(a)):
    print("% d" % a[i])


C#
// C# program for implementation of Cocktail Sort
using System;
 
class GFG {
 
    static void cocktailSort(int[] a)
    {
        bool swapped = true;
        int start = 0;
        int end = a.Length;
 
        while (swapped == true) {
 
            // reset the swapped flag on entering the
            // loop, because it might be true from a
            // previous iteration.
            swapped = false;
 
            // loop from bottom to top same as
            // the bubble sort
            for (int i = start; i < end - 1; ++i) {
                if (a[i] > a[i + 1]) {
                    int temp = a[i];
                    a[i] = a[i + 1];
                    a[i + 1] = temp;
                    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 top to bottom, doing the
            // same comparison as in the previous stage
            for (int i = end - 1; i >= start; i--) {
                if (a[i] > a[i + 1]) {
                    int temp = a[i];
                    a[i] = a[i + 1];
                    a[i + 1] = temp;
                    swapped = true;
                }
            }
 
            // increase the starting point, because
            // the last stage would have moved the next
            // smallest number to its rightful spot.
            start = start + 1;
        }
    }
 
    /* Prints the array */
    static void printArray(int[] a)
    {
        int n = a.Length;
        for (int i = 0; i < n; i++)
            Console.Write(a[i] + " ");
        Console.WriteLine();
    }
 
    // Driver code
    public static void Main()
    {
        int[] a = { 5, 1, 4, 2, 8, 0, 2 };
        cocktailSort(a);
        Console.WriteLine("Sorted array ");
        printArray(a);
    }
}
 
// This code is contributed by Sam007


输出
Sorted array :
0 1 2 2 4 5 8 

最坏情况和平均情况下的时间复杂度: O(n * n)。
最佳情况下的时间复杂度: O(n)。最好的情况是对数组进行排序时。
辅助空间: O(1)
到位排序:
稳定:是的
与冒泡排序比较:
时间复杂度相同,但鸡尾酒的性能优于气泡排序。通常,鸡尾酒分选比气泡分选快不到两倍。考虑示例(2、3、4、5、1)。在此示例中,冒泡排序需要四个遍历数组,而鸡尾酒排序仅需要两个遍历。 (资料来源Wiki)
参考:

  • https://zh.wikipedia.org/wiki/Cocktail_shaker_sort
  • http://will.thimbleby.net/algorithms/doku。 PHP?id = cocktail_sort
  • http://www.programming-algorithms.net/article/40270/Shaker-sort