/* Shuffle sort a.k.a. "cocktail sort" */

Data >>
 A : Array
 Flag : Integer : 1 | 0
;

/* * */

ArraySort ->
Arg Array : ^&Array, 
    . : SHUFFLE_SORT

Begin = 0 ..
End = Array._ - 1 ..

Flag = 1 ..

Do while Flag = 1
 Call LeftToRight Begin End 'Array Flag'
 After Flag = 0; Begin ++

 If Flag then
  Call RightToLeft Begin End 'Array Flag'
  After Flag = 0; End --
 ;
;

Return

/* Walking up the array.
   This function will move the greatest element 
   to the right bound of the array */

LeftToRight ArraySort ->
Arg Begin, End : Integer, A : ^&Data

Do Swapping i 'A'
Where i = Begin to End

Return

/* Walking down the array.
   This function will move the lowest element 
   to the left bound of the array */

RightToLeft ArraySort ->
Arg Begin, End : Integer, A : ^&Data

Do Swapping i 'A'
Where i = End to Begin step -1

Return

/* Swapping two neighbors */

Swapping LeftToRight, RightToLeft ->
Arg First : Integer, A : ^&Data

Second = First + 1

If A.A.First > A.A.Second then
 A.A.First = A.A.Second = A.A.First
 A.Flag = 1
;

Return

/* * */

Export ArraySort