You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

请用渐近表示法表示下述函数的最优与最坏情况时间复杂度

Let's break down this function and analyze its time complexity—first, a quick note: this is cocktail shaker sort (also called bidirectional bubble sort), a variation of standard bubble sort that sorts in both left-to-right and right-to-left passes. Here's the breakdown of its best and worst-case asymptotic time complexity:

First, let's restate the function for clarity:

function(A[], n):
    swapped = true
    start = 0
    end = n-1
    while swapped == true
        swapped = false
        for i = start to end-1
            if A[i] > A[i+1]
                swap(A[i], A[i+1])
                swapped = true
        if swapped == false
            break
        end = end-1
        swapped = false
        for i = end-1 down to start
            if A[i] > A[i+1]
                swap(A[i], A[i+1])
                swapped = true
        if swapped == false
            break
        start = start+1

Optimal (Best-Case) Time Complexity: O(n)

This happens when the input array is already fully sorted:

  • The first left-to-right pass runs through all n elements, but no swaps occur (since every element is in order). The swapped flag stays false.
  • The loop breaks immediately after this first pass—no additional iterations or reverse passes are executed.
  • The total work is just a single linear scan of the array, hence the O(n) time complexity.

Worst-Case Time Complexity: O(n²)

This occurs when the input array is completely reversed (sorted in descending order):

  • Each full iteration (left-to-right pass + right-to-left pass) moves the largest unsorted element to its correct position at the end, and the smallest unsorted element to its correct position at the start.
  • We need roughly n/2 such full iterations to sort the entire array.
  • Each iteration involves scanning most of the remaining unsorted elements. The total number of comparisons/swaps sums up to a quadratic value: (n-1) + (n-3) + (n-5) + ... ≈ n²/2, which simplifies to O(n²).

A quick side note: While cocktail shaker sort performs better than standard bubble sort for arrays with small elements stuck near the end, it's still a comparison-based sort with the same upper asymptotic bound as bubble sort.

内容的提问来源于stack exchange,提问作者ashraf pitu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 22:53:11