Never been to CodeSnippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world (or not, you can keep them private!)

About this user

1 total

On This Page:

  1. 1 cocktail Sort

cocktail Sort

cocktail sort in C++
Cocktail sort, also known as bidirectional bubble sort, cocktail shaker sort, shaker sort (which can also refer to a variant of selection sort), ripple sort, shuttle sort or happy hour sort, is a variation of bubble sort that is both a stable sorting algorithm and a comparison sort. The algorithm differs from bubble sort in that sorts in both directions each pass through the list.

void cocktail_sort (int A[], int n)
{
    int left = 0, right = n;
    bool finished;
    do
    {
        finished = true;
        --right;
        for (int i = left; i < right; i++)
            if (A[i] > A[i+1]) {
                std::swap(A[i], A[i+1]);
                finished = false;
            }
        if (finished) return;
        finished = true;
        for (int i = right; i > left; i--)
            if (A[i] < A[i-1]) {
                std::swap(A[i], A[i-1]);
                finished = false;
            }
        ++left;
    } while (!finished);
}
1 total

On This Page:

  1. 1 cocktail Sort