Cocktail Sort

Cocktail sort, also known as bidirectional bubble sort, cocktail shaker sort, shaker sort, or shuttle sort, is a stable sorting algorithm that varies from bubble sort in that instead of repeatedly passing through the list from top to bottom, it passes alternately from top to bottom and then from bottom to top.
Complexity in Big O notation is O(n²) for a worst case, but becomes closer to O(n) if the list is mostly ordered at the beginning.

Implementation

C++

  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 (Ai > Ai+1) {                  std::swap(Ai, Ai+1);                  finished = false;              }          if (finished) return; finished = true;          for (int i = right; i > left; i--)              if (Ai < Ai-1) {                  std::swap(Ai, Ai-1);                  finished = false;              }          ++left;      } while (!finished);  } 

Perl

  sub cocktail_sort(@)  {    my @a = @_;    my ($left,$right) = (0,$#_);    while ($left < $right) {      foreach $i ($left..$right-1) {        ($a$i,$a$i+1) = ($a$i+1,$a$i) if ($a$i > $a$i+1);      }      $right--;      foreach $i (reverse $left+1..$right) {        ($a$i,$a$i-1) = ($a$i-1,$a$i) if ($a$i < $a$i-1);      }      $left++;    }    return @a;  } 

 

<< PreviousWord BrowserNext >>
greenbelt festival
urination
servant
arab american
arab world
mordred
comb sort
type metal
drusilla (buffy the vampire slayer)
the negotiator
nakba
nebraska cornhuskers
g. i. gurdjieff
closer (album)
the the
public transport service numbering
closer
mount kilimanjaro
intonation
international phonetic association
mind bomb
flight
edward norton
bilingual
everclear (band)
the melvins
needle lace
crocheted lace
static x
danzig (band)
glenn danzig
gloria trevi
triangle (instrument)
david r. morgan
robert e. england
recall
initiative
alpha beta pruning
mayor council government
additive color
rgb color space
spectralism
phoebe cates
barnacle