Python实现鸡尾酒排序算法

2023-04-16 00:00:00 算法 排序 鸡尾酒

鸡尾酒排序(Cocktail Sort),也叫双向冒泡排序(Bidirectional Bubble Sort),是冒泡排序的一种变形。它的原理是从左到右扫描数列,然后把最大的数移到右边;再从右到左扫描数列,把最小的数移到左边;以此类推,交替进行,直到整个数列有序。这样,排序的效率比冒泡排序要高一些。

以下是Python实现鸡尾酒排序算法的代码:

def cocktail_sort(arr):
    left, right = 0, len(arr) - 1
    while left < right:
        for i in range(left, right):  # 从左到右扫描并把最大的数移到右边
            if arr[i] > arr[i + 1]:
                arr[i], arr[i + 1] = arr[i + 1], arr[i]
        right -= 1
        for i in range(right, left, -1):  # 从右到左扫描并把最小的数移到左边
            if arr[i] < arr[i - 1]:
                arr[i], arr[i - 1] = arr[i - 1], arr[i]
        left += 1
    return arr

我们可以使用一些测试用例来验证算法的正确性:

print(cocktail_sort([3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]))  # [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]
print(cocktail_sort([5, 4, 3, 2, 1]))  # [1, 2, 3, 4, 5]
print(cocktail_sort([1, 2, 3, 4, 5]))  # [1, 2, 3, 4, 5]
print(cocktail_sort(["p", "i", "d", "a", "n", "c", "o", "d", "e", ".", "c", "o", "m"]))  # [".", "c", "c", "d", "d", "e", "e", "i", "m", "n", "o", "o", "p"]
print(cocktail_sort(["皮", "蛋", "编", "程", "是", "一", "个", "好", "网", "站"]))  # ["一", "个", "编", "程", "好", "是", "网", "站", "蛋", "皮"]

从上面的测试结果来看,鸡尾酒排序算法是正确的。

相关文章