
Sorting Algorithm

This is a sorting algorithm.   It may be applied to a set of data in order to sort it.    
For comparing various sorts, see compare sorts.  
For other sorting algorithms,   see sorting algorithms,   or:

O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort




 This page uses content from Wikipedia. The original article was at Cocktail sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)



The   cocktail sort   is an improvement on the   Bubble Sort.



A cocktail sort is also known as:

   cocktail shaker sort
   happy hour sort
   bidirectional bubble sort
   a bubble sort variation
   a selection sort variation
   ripple sort
   shuffle sort
   shuttle sort


The improvement is basically that values "bubble"   (migrate)   both directions through the
array,   because on each iteration the cocktail sort   bubble sorts   once
forwards and once backwards.

After   ii   passes,   the first   ii   and the
last   ii   elements in the array are in their correct
positions,   and don't have to be checked (again).

By shortening the part of the array that is sorted each time,   the number of
comparisons can be halved.



Pseudocode for the    2nd    algorithm   (from
Wikipedia)   with an added comment and changed indentations:

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  (below)  decrements the  II  index by -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
%   indicates a comment,   and   deal   indicates a   swap.



Task

Implement a   cocktail sort   and optionally show the sorted output here on this page.

See the   discussion   page for some timing comparisons.



Related task

   cocktail sort


#include <algorithm>
#include <cassert>
#include <iostream>
#include <iterator>
#include <vector>
 
// This only works for random access iterators
template <typename iterator>
void cocktail_shaker_sort(iterator begin, iterator end) {
    if (begin == end)
        return;
    for (--end; begin < end; ) {
        iterator new_begin = end;
        iterator new_end = begin;
        for (iterator i = begin; i < end; ++i) {
            iterator j = i + 1;
            if (*j < *i) {
                std::iter_swap(i, j);
                new_end = i;
            }
        }
        end = new_end;
        for (iterator i = end; i > begin; --i) {
            iterator j = i - 1;
            if (*i < *j) {
                std::iter_swap(i, j);
                new_begin = i;
            }
        }
        begin = new_begin;
    }
}
 
template <typename iterator>
void print(iterator begin, iterator end) {
    if (begin == end)
        return;
    std::cout << *begin++;
    while (begin != end)
        std::cout << ' ' << *begin++;
    std::cout << '\n';
}
 
int main() {
    std::vector<int> v{5, 1, -6, 12, 3, 13, 2, 4, 0, 15};
    std::cout << "before: ";
    print(v.begin(), v.end());
    cocktail_shaker_sort(v.begin(), v.end());
    assert(std::is_sorted(v.begin(), v.end()));
    std::cout << "after: ";
    print(v.begin(), v.end());
    return 0;
}