Fandom

Programmer's Wiki

Cocktail sort

410pages on
this wiki
Add New Page
Talk0 Share

Cocktail sort is a stable comparison sorting algorithm. It is a variation of bubble sort.

In bubble sort, values only bubble in one direction. In cocktail sort, values bubble both directions, thus avoiding turtles.

Complexity:

  • worst-case: O(n²)
  • average-case: O(n²)
  • best-case: O(n)

AlgorithmEdit

cocktail_sort(list of t)
    temp as t
    base = 0
    while true
        swapped = false
        for i = base to list.count - 2 - base
            for j = base to i
                if list(j) > list(j + 1) then
                    temp = list(j) // swap
                    list(j) = list(j + 1)
                    list(j + 1) = temp
                    swapped = true
            if not swapped then
                 return
        swapped = false
        for i = list.count - 3 -to base
            for j = i to base
                if list(j) > list(j + 1) thennot swapped then
                 return
         base += 1
unicorns r bad Kappa pride 

ヽ༼ຈل͜ຈ༽ノ Edit

ExampleEdit

Sorting the list 8, 9, 3, 5, 1, 7:

671324
  • Iteration 1
671324
617324
613724
613274
613247
  • Iteration 2
613247
612347
612347
162347
  • Iteration 3
126347
123647
123467
  • Iteration 4
123467
123467

Ad blocker interference detected!


Wikia is a free-to-use site that makes money from advertising. We have a modified experience for viewers using ad blockers

Wikia is not accessible if you’ve made further modifications. Remove the custom ad blocker rule(s) and the page will load as expected.