Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Cocktail shaker sort
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
{{Short description|Sorting algorithm}} {{Infobox Algorithm |class=[[Sorting algorithm]] |image=[[File:Sorting shaker sort anim.gif|Visualization of shaker sort]] |data=[[Array data structure|Array]] |best-time= <math>O(n)\,</math> |average-time= <math>O(n^2)\,</math> |time=<math>O(n^2)\,</math> |space=<math>O(1)</math> |optimal=No }} '''Cocktail shaker sort''',<ref name="Knuth">{{cite book|title=Art of Computer Programming|edition=1st|pages=110–111|last=Knuth|first=Donald E.|author-link=Donald Knuth|volume=3. Sorting and Searching|chapter=Sorting by Exchanging|publisher=[[Addison-Wesley]]|date=1973|isbn=0-201-03803-X}}</ref> also known as '''bidirectional bubble sort''',<ref>{{cite book|first1=Paul E.|last1=Black|first2=Bob|last2=Bockholt|url=http://xlinux.nist.gov/dads/HTML/bidirectionalBubbleSort.html|chapter=bidirectional bubble sort|title=Dictionary of Algorithms and Data Structures|editor1-first=Paul E.|editor1-last=Black|publisher=[[National Institute of Standards and Technology]]|date=24 August 2009|access-date=5 February 2010|archive-url=https://web.archive.org/web/20130316180005/http://xlinux.nist.gov/dads//HTML/bidirectionalBubbleSort.html|archive-date=16 March 2013|url-status=dead}}</ref> '''cocktail sort''', '''shaker sort''' (which can also refer to a variant of [[selection sort]]), '''ripple sort''', '''shuffle sort''',<ref name="Duhl1986">{{cite book|first=Martin|last=Duhl|contribution=Die schrittweise Entwicklung und Beschreibung einer Shuffle-Sort-Array Schaltung|title=HYPERKARL aus der Algorithmischen Darstellung des BUBBLE-SORT-ALGORITHMUS|language=de|journal=Projektarbeit|year=1986|publisher=Technical University of Kaiserslautern}}</ref> or '''shuttle sort''', is an extension of [[bubble sort]]. The algorithm extends bubble sort by operating in two directions. While it improves on bubble sort by more [[Bubble sort#Rabbits and turtles|quickly moving items to the beginning of the list]], it provides only marginal performance improvements. Like most variants of bubble sort, cocktail shaker sort is used primarily as an educational tool. More efficient algorithms such as [[quicksort]], [[merge sort]], or [[timsort]] are used by the sorting libraries built into popular programming languages such as Python and Java.<ref>{{Cite web|url=https://bugs.openjdk.java.net/browse/JDK-6804124|title=[JDK-6804124] (coll) Replace "modified mergesort" in java.util.Arrays.sort with timsort - Java Bug System|website=bugs.openjdk.java.net|access-date=2020-01-11}}</ref><ref>{{Cite web|url=https://mail.python.org/pipermail/python-dev/2002-July/026837.html|title=[Python-Dev] Sorting|last=Peters|first=Tim|date=2002-07-20|access-date=2020-01-11}}</ref> ==Pseudocode== The simplest form goes through the whole list each time: '''procedure''' cocktailShakerSort(A ''':''' list of sortable items) '''is''' '''do''' swapped := false '''for each''' i '''in''' 0 '''to''' length(A) β 1 '''do:''' '''if''' A[i] > A[i + 1] '''then''' <span style="color:green">// test whether the two elements are in the wrong order</span> swap(A[i], A[i + 1]) <span style="color:green">// let the two elements change places</span> swapped := true '''end if''' '''end for''' '''if not''' swapped '''then''' <span style="color:green">// we can exit the outer loop here if no swaps occurred.</span> '''break do-while loop''' '''end if''' swapped := false '''for each''' i '''in''' length(A) β 1 '''to''' 0 '''do:''' '''if''' A[i] > A[i + 1] '''then''' swap(A[i], A[i + 1]) swapped := true '''end if''' '''end for''' '''while''' swapped <span style="color:green">// if no elements have been swapped, then the list is sorted</span> '''end procedure''' The first rightward pass will shift the largest element to its correct place at the end, and the following leftward pass will shift the smallest element to its correct place at the beginning. The second complete pass will shift the second largest and second smallest elements to their correct places, and so on. After ''i'' passes, the first ''i'' and the last ''i'' elements in the list are in their correct positions, and do not need to be checked. By shortening the part of the list that is sorted each time, the number of operations can be halved (see [[Bubble_sort#Alternative_implementations|bubble sort]]). This is an example of the algorithm in MATLAB/OCTAVE with the optimization of remembering the last swap index and updating the bounds. <syntaxhighlight lang="matlab"> function A = cocktailShakerSort(A) % `beginIdx` and `endIdx` marks the first and last index to check beginIdx = 1; endIdx = length(A) - 1; while beginIdx <= endIdx newBeginIdx = endIdx; newEndIdx = beginIdx; for ii = beginIdx:endIdx if A(ii) > A(ii + 1) [A(ii+1), A(ii)] = deal(A(ii), A(ii+1)); newEndIdx = ii; end end % decreases `endIdx` because the elements after `newEndIdx` are in correct order endIdx = newEndIdx - 1; for ii = endIdx:-1:beginIdx if A(ii) > A(ii + 1) [A(ii+1), A(ii)] = deal(A(ii), A(ii+1)); newBeginIdx = ii; end end % increases `beginIdx` because the elements before `newBeginIdx` are in correct order beginIdx = newBeginIdx + 1; end end </syntaxhighlight> ==Differences from bubble sort== Cocktail shaker sort is a slight variation of [[bubble sort]].<ref name="Knuth"/> It differs in that instead of repeatedly passing through the list from bottom to top, it passes alternately from bottom to top and then from top to bottom. It can achieve slightly better performance than a standard bubble sort. The reason for this is that [[bubble sort]] only passes through the list in one direction and therefore can only move items backward one step each iteration. An example of a list that proves this point is the list (2,3,4,5,1), which would only need to go through one pass of cocktail sort to become sorted, but if using an ascending [[bubble sort]] would take four passes. However one cocktail sort pass should be counted as two bubble sort passes. Typically cocktail sort is less than two times faster than bubble sort. Another optimization can be that the algorithm remembers where the last actual swap has been done. In the next iteration, there will be no swaps beyond this limit and the algorithm has shorter passes. As the cocktail shaker sort goes bidirectionally, the range of possible swaps, which is the range to be tested, will reduce per pass, thus reducing the overall running time slightly. ==Complexity== The complexity of the cocktail shaker sort in [[big O notation]] is <math>O(n^2)</math> for both the worst case and the average case, but it becomes closer to <math>O(n)</math> if the list is mostly ordered before applying the sorting algorithm. For example, if every element is at a position that differs by at most k (k β₯ 1) from the position it is going to end up in, the complexity of cocktail shaker sort becomes <math>O(kn).</math> The cocktail shaker sort is also briefly discussed in the book ''[[The Art of Computer Programming]]'', along with similar refinements of bubble sort. In conclusion, Knuth states about bubble sort and its improvements: {{quote|But none of these refinements leads to an algorithm better than straight insertion [that is, [[insertion sort]]]; and we already know that straight insertion isn't suitable for large ''N''. [...] In short, the bubble sort seems to have nothing to recommend it, except a catchy name and the fact that it leads to some interesting theoretical problems.|D. E. Knuth<ref name="Knuth"/> }} ==Variations== * Dual Cocktail Shaker sort is a variant of Cocktail Shaker Sort that performs a forward and backward pass per iteration simultaneously, improving performance compared to the original. ==References== {{Reflist}} ==Sources== *{{cite journal|first=R.|last=Hartenstein|journal=The Grand Challenge to Reinvent Computing|title=A new World Model of Computing|publisher=CSBC|date=July 2010|place=[[Belo Horizonte]], Brazil|url=http://www.inf.pucminas.br/sbc2010/anais/pdf/semish/st03_02.pdf|access-date=2011-01-14|archive-url=https://web.archive.org/web/20130807043613/http://www.inf.pucminas.br/sbc2010/anais/pdf/semish/st03_02.pdf|archive-date=2013-08-07|url-status=dead}} ==External links== {{Wikibooks|Algorithm implementation|Sorting/Cocktail sort|Cocktail sort}} *[http://www.hermann-gruber.com/lehre/sorting/Shaker/Shaker-en.html Interactive demo of cocktail sort] *[https://web.archive.org/web/20061008105719/http://www.cs.ubc.ca/~harrison/Java/sorting-demo.html Java source code and an animated demo of cocktail sort (called bi-directional bubble sort) and several other algorithms] *{{cite web |url=http://www.sharpdeveloper.net/content/archive/2007/08/14/dot-net-data-structures-and-algorithms.aspx |archive-url=https://web.archive.org/web/20120212173240/http://www.sharpdeveloper.net/content/archive/2007/08/14/dot-net-data-structures-and-algorithms.aspx |title=.NET Implementation of cocktail sort and several other algorithms |archive-date=2012-02-12}} {{sorting}} {{DEFAULTSORT:Cocktail Sort}} [[Category: Articles with example pseudocode]] [[Category: Comparison sorts]] [[Category: Stable sorts]]
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)
Pages transcluded onto the current version of this page
(
help
)
:
Template:Cite book
(
edit
)
Template:Cite journal
(
edit
)
Template:Cite web
(
edit
)
Template:Infobox Algorithm
(
edit
)
Template:Quote
(
edit
)
Template:Reflist
(
edit
)
Template:Short description
(
edit
)
Template:Sorting
(
edit
)
Template:Wikibooks
(
edit
)