Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lære 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).

Oppgave

Swipe to start coding

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

Løsning

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)

Alt var klart?

Hvordan kan vi forbedre det?

Takk for tilbakemeldingene dine!

Seksjon 1. Kapittel 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
toggle bottom row
some-alt