Last modified on 27 November 2014, at 12:07

Algorithm Implementation/Sorting/Cocktail sort

JavaEdit

public static int[] cocktailSort(int[] numbers) 
{
      boolean swapped = true;
      int i = 0;
      int j = numbers.length - 1;
      while(i < j && swapped) 
      {
         swapped = false;
         for(int k = i; k < j; k++) 
         {
            if(numbers[k] > numbers[k + 1]) 
            {
               int temp = numbers[k];
               numbers[k] = numbers[k + 1];
               numbers[k + 1] = temp;
               swapped = true;
            }
         }
         j--;
         if(swapped) 
         {
            swapped = false;
            for(int k = j; k > i; k--) 
            {
               if(numbers[k] < numbers[k - 1]) 
               {
                  int temp = numbers[k];
                  numbers[k] = numbers[k - 1];
                  numbers[k - 1] = temp;
                  swapped = true;
               }
            }
         }
         i++;
      }
      return numbers;    
}

PerlEdit

sub swap {
    @_[ 0, 1 ] = @_[ 1, 0 ];
    return 1;
}
 
sub cocktail_sort {
    # returns a sorted copy
    my @a = @_;
    for ( my $swapped = 1 ; $swapped ; ) {
        for ( $swapped = 0, my $i = 0 ; $i < ( $#a - 1 ) ; $i += 1 ) {
            $swapped = swap $a[ $i + 1 ], $a[$i] if $a[$i] > $a[ $i + 1 ];
        }
        for ( $swapped = 0, my $i = ( $#a - 1 ) ; $i > 0 ; $i -= 1 ) {
            $swapped = swap $a[ $i + 1 ], $a[$i] if $a[$i] > $a[ $i + 1 ];
        }
    }
    wantarray ? @a : \@a;
}

PythonEdit

def cocktail_sort(A):
    for k in range(len(A)-1, 0, -1):
        swapped = False
        for i in range(k, 0, -1):
            if A[i]<A[i-1]:
                A[i], A[i-1] = A[i-1], A[i]
                swapped = True
 
        for i in range(k):
            if A[i] > A[i+1]:
                A[i], A[i+1] = A[i+1], A[i]
                swapped = True
 
        if not swapped:
            return A

VB.NETEdit

    Public Sub cocktailsort(ByRef a() As Integer)
        Dim i As Integer = 0
        Dim num As Integer = 0
        Do
            num = 0
            While Not i = a.Length - 1
                If a(i) > a(i + 1) Then
                    swap(a(i), a(i + 1))
                    num += 1
                End If
                i += 1
            End While
            If num = 0 Then
                Exit Do
            End If
            While Not i = 0
                If a(i) < a(i - 1) Then
                    swap(a(i), a(i - 1))
                    num += 1
                End If
                i -= 1
            End While
        Loop Until num = 0
    End Sub