Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Aprenda Cocktail Sort | Simple Algorithms
Sorting Algorithms

book
Cocktail Sort

Cocktail sort is another kind of Bubble sort. In Bubble sort, we traverse the array from left to right to push the greatest element to the end of the unsorted part. In Cocktail sort, we do iterations in both directions: first move the greatest element to the right, then move the least element to the left, and then repeat it again until array is sorted.

Example 1

Time Complexity: O(N^2).

Space Complexity: O(1).

Tarefa

Swipe to start coding

Follow the comments to complete the Cocktail Sort algorithm. Add missing lines to code.

Solução

def cocktailSort(arr):
for i in range(0, len(arr)-1, 2):

# traverse from left to right
for j in range(len(arr)-i-1):
if arr[j+1] < arr[j]:
arr[j], arr[j+1] = arr[j+1], arr[j]

# traverse from right to left
for j in range(len(arr)-i-2, i+1, -1):
if arr[j-1] > arr[j]:
arr[j], arr[j-1] = arr[j-1], arr[j]

arr = [6,3,-2,-3,2,1,7,5]
cocktailSort(arr)
print(arr)

Tudo estava claro?

Como podemos melhorá-lo?

Obrigado pelo seu feedback!

Seção 1. Capítulo 7
def cocktailSort(arr):
# Do n//2 steps, each 2 passes
for i in range(0, len(arr)-1, 2):

# Traverse from left to right
for j in range(len(arr)-i-1):
if _ _ _ _:
arr[j], arr[j+1] = arr[j+1], arr[j]

# Traverse from right to left
for j in range(len(arr)-i-2, i+1, -1):
if _ _ _ _:
_ _ _ _ # Swap elements

arr = [6,3,-2,-3,2,1,7,5]
# Call the function for arr
# Print the sorted arr

Pergunte à IA

expand
ChatGPT

Pergunte o que quiser ou experimente uma das perguntas sugeridas para iniciar nosso bate-papo

some-alt