proc innerCircleSort[T](a: var openArray[T], lo, hi, swaps: int): int =
  var localSwaps: int = swaps
  var localHi: int = hi
  var localLo: int = lo
  if localLo == localHi:
    return swaps

  var `high` = localHi
  var `low` = localLo
  var mid = (localHi - localLo) div 2

  while localLo < localHi:
    if a[localLo] > a[localHi]:
      swap a[localLo], a[localHi]
      inc localSwaps
    inc localLo
    dec localHi
  if localLo == localHi:
    if a[localLo] > a[localHi + 1]:
      swap a[localLo], a[localHi + 1]
      inc localSwaps

  localswaps = a.innerCircleSort(`low`, `low` + mid, localSwaps)
  localSwaps = a.innerCircleSort(`low` + mid + 1, `high`, localSwaps)
  result = localSwaps

proc circleSort[T](a: var openArray[T]) =
  while a.innerCircleSort(0, a.high, 0) != 0:
    discard

var arr = @[@[6, 7, 8, 9, 2, 5, 3, 4, 1],
            @[2, 14, 4, 6, 8, 1, 3, 5, 7, 11, 0, 13, 12, -1]]

for i in 0..arr.high:
  echo "Original: ", $arr[i]
  arr[i].circleSort()
  echo "Sorted: ", $arr[i], if i != arr.high: "\n" else: ""


class CircleSort {
  function : Main(args : String[]) ~ Nil {
    circleSort([2, 14, 4, 6, 8, 1, 3, 5, 7, 11, 0, 13, 12, -1]);
  }

  function : circleSort(arr : Int[]) ~ Nil {
    if(arr->Size() > 0) {
      do {
        arr->ToString()->PrintLine();
      }
      while(CircleSort(arr, 0, arr->Size() - 1, 0) <> 0);
    };
  }

  function : CircleSort( arr : Int[], lo : Int, hi : Int, num_swaps : Int) ~ Int {
    if(lo = hi) {
      return num_swaps;
    };

    high := hi;
    low := lo;
    mid := (hi - lo) / 2;

    while (lo < hi) {
      if(arr[lo] > arr[hi]) {
        Swap(arr, lo, hi);
        num_swaps++;
      };
      lo++;
      hi--;
    };

    if(lo = hi & arr[lo] > arr[hi + 1]) {
      Swap(arr, lo, hi + 1);
      num_swaps++;
    };

    num_swaps := CircleSort(arr, low, low + mid, num_swaps);
    num_swaps := CircleSort(arr, low + mid + 1, high, num_swaps);

    return num_swaps;
  }

  function : Swap(arr : Int[], idx1 : Int, idx2 : Int) ~ Nil {
    tmp := arr[idx1];
    arr[idx1] := arr[idx2];
    arr[idx2] := tmp;
  }
}


circlesort(v)=
{
	local(v=v); \\ share with cs
	while (cs(1, #v),);
	v;
}
cs(lo, hi)=
{
	if (lo == hi, return (0));
	my(high=hi,low=lo,mid=(hi-lo)\2,swaps);
	while (lo < hi,
		if (v[lo] > v[hi],
			[v[lo],v[hi]]=[v[hi],v[lo]];
			swaps++
		);
		lo++;
		hi--
	);
	if (lo==hi && v[lo] > v[hi+1],
		[v[lo],v[hi+1]]=[v[hi+1],v[lo]];
		swaps++
	);
	swaps + cs(low,low+mid) + cs(low+mid+1,high);
}
print(example=[6,7,8,9,2,5,3,4,1]);
print(circlesort(example));


{
   source file name on linux is ./p.p

   -*- mode: compilation; default-directory: "/tmp/" -*-
   Compilation started at Sat Mar 11 23:55:25

   a=./p && pc $a.p && $a
   Free Pascal Compiler version 3.0.0+dfsg-8 [2016/09/03] for x86_64
   Copyright (c) 1993-2015 by Florian Klaempfl and others
   Target OS: Linux for x86-64
   Compiling ./p.p
   Linking p
   /usr/bin/ld.bfd: warning: link.res contains output sections; did you forget -T?
   56 lines compiled, 0.0 sec
   1 2 3 4 5 6 7 8 9

   Compilation finished at Sat Mar 11 23:55:25
}

program sort;

var
   a : array[0..999] of integer;
   i :  integer;

procedure circle_sort(var a : array of integer; left : integer; right : integer);
var swaps : integer;

   procedure csinternal(var a : array of integer; left : integer; right : integer; var swaps : integer);
   var
      lo, hi, mid : integer;
      t           : integer;
   begin
      if left < right then
      begin
	 lo := left;
	 hi := right;
	 while lo < hi do
	 begin
	    if a[hi] < a[lo] then
	    begin
	       t := a[lo]; a[lo] := a[hi]; a[hi] := t;
	       swaps := swaps + 1;
	    end;
	    lo := lo + 1;
	    hi := hi - 1;
	 end;
	 if (lo = hi) and (a[lo+1] < a[lo]) then
	 begin
	    t := a[lo]; a[lo] := a[lo+1]; a[lo+1] := t;
	    swaps := swaps + 1;
	 end;
	 mid := trunc((hi + lo) / 2);
	 csinternal(a, left, mid, swaps);
	 csinternal(a, mid + 1, right, swaps)
      end
   end;

begin;
   swaps := 1;
   while (0 < swaps) do
   begin
      swaps := 0;
      csinternal(a, left, right, swaps);
   end
end;

begin
   {
      generating polynomial coefficients computed in j:  6 7 8 9 2 5 3 4 1x %. ^/~i.9x
      are 6 29999r280 _292519r1120 70219r288 _73271r640 10697r360 _4153r960 667r2016 _139r13440
   }
   a[1]:=6;a[2]:=7;a[3]:=8;a[4]:=9;a[5]:=2;a[6]:=5;a[7]:=3;a[8]:=4;a[9]:=1;
   circle_sort(a,1,9);
   for i := 1 to 9 do write(a[i], ' ');
   writeln();
end.


sub circlesort {
    our @x; local *x = shift;
    my($beg,$end) = @_;

    my $swaps = 0;
    if ($beg < $end) {
        my $lo = $beg;
        my $hi = $end;
        while ($lo < $hi) {
            if ($x[$lo] > $x[$hi]) { # 'gt' here for string comparison
                @x[$lo,$hi] = @x[$hi,$lo];
                ++$swaps;
            }
            ++$hi if --$hi == ++$lo
        }
        $swaps += circlesort(\@x, $beg, $hi);
        $swaps += circlesort(\@x, $lo, $end);
    }
    $swaps;
}

my @a = <16 35 -64 -29 46 36 -1 -99 20 100 59 26 76 -78 39 85 -7 -81 25 88>;
while (circlesort(\@a, 0, $#a)) { print join(' ', @a), "\n" }


with javascript_semantics

sequence array

function circle_sort_inner(integer lo, hi, swaps, level=1)
    if lo!=hi then
        integer high := hi,
                low := lo,
                mid := floor((high-low)/2)
        while lo <= hi do
            hi += (lo=hi)
            object alo = array[lo],
                   ahi = array[hi]
            if alo > ahi then
                array[lo] = ahi
                array[hi] = alo
                printf(1,"%V level %d, low %d, high %d\n",{array,level,low,high})
                swaps += 1
            end if
            lo += 1
            hi -= 1
        end while
        swaps = circle_sort_inner(low,low+mid,swaps,level+1)
        swaps = circle_sort_inner(low+mid+1,high,swaps,level+1)
    end if
    return swaps
end function

procedure circle_sort()
    printf(1,"%V <== (initial)\n",{array})
    while circle_sort_inner(1, length(array), 0) do ?"loop" end while
    printf(1,"%V <== (sorted)\n",{array})
end procedure

array = {5, -1, 101, -4, 0, 1, 8, 6, 2, 3}
--array = {-4,-1,1,0,5,-7,-2,4,-6,-3,2,6,3,7,-5}
--array = {6, 7, 8, 9, 2, 5, 3, 4, 1}
--array = {2,14,4,6,8,1,3,5,7,9,10,11,0,13,12,-1}
--array = {"the","quick","brown","fox","jumps","over","the","lazy","dog"}
--array = {0.603704, 0.293639, 0.513965, 0.746246, 0.245282, 0.930508, 0.550878, 0.622534, 0.006089, 0.270426}
--array = shuffle(deep_copy(array))
circle_sort()


#python3
#tests: expect no output.
#doctest with  python3 -m doctest thisfile.py
#additional tests:  python3 thisfile.py

def circle_sort_backend(A:list, L:int, R:int)->'sort A in place, returning the number of swaps':
    '''
        >>> L = [3, 2, 8, 28, 2,]
        >>> circle_sort(L)
        3
        >>> print(L)
        [2, 2, 3, 8, 28]
        >>> L = [3, 2, 8, 28,]
        >>> circle_sort(L)
        1
        >>> print(L)
        [2, 3, 8, 28]
    '''
    n = R-L
    if n < 2:
        return 0
    swaps = 0
    m = n//2
    for i in range(m):
        if A[R-(i+1)] < A[L+i]:
            (A[R-(i+1)], A[L+i],) = (A[L+i], A[R-(i+1)],)
            swaps += 1
    if (n & 1) and (A[L+m] < A[L+m-1]):
        (A[L+m-1], A[L+m],) = (A[L+m], A[L+m-1],)
        swaps += 1
    return swaps + circle_sort_backend(A, L, L+m) + circle_sort_backend(A, L+m, R)

def circle_sort(L:list)->'sort A in place, returning the number of swaps':
    swaps = 0
    s = 1
    while s:
        s = circle_sort_backend(L, 0, len(L))
        swaps += s
    return swaps

# more tests!
if __name__ == '__main__':
    from random import shuffle
    for i in range(309):
        L = list(range(i))
        M = L[:]
        shuffle(L)
        N = L[:]
        circle_sort(L)
        if L != M:
            print(len(L))
            print(N)
            print(L)


  [ dup size 2 < iff
      [ drop true ] done
    true swap
    dup [] != if
      [ behead swap witheach
        [ tuck > if
          [ dip not
            conclude ] ] ]
    drop ]                    is sorted     ( [ --> b   )

  [ behead swap witheach
      [ 2dup < iff
        nip else drop ] ]     is largest    ( [ --> n   )

  [ dup largest 1+
    over size
    dup 1
    [ 2dup > while
      1 << again ]
    nip swap -
    dup dip [ of join ]
    swap ]                    is pad        (   [ --> n [ )

  [ swap dup if
      [ negate split drop ] ] is unpad      ( n [ --> [   )

  [ dup size times
    [ i i^ > not iff
        conclude done
      dup i peek
      over i^ peek
      2dup < iff
        [ rot i poke
          i^ poke ]
      else 2drop ] ]          is reorder    (   [ --> [   )

  [ pad
    [ [ dup sorted if done
        reorder
        dup size 2 / split
        recurse swap
        recurse swap join ]
      dup sorted until ]
    unpad ]                   is circlesort (   [ --> [   )

  $ "bababadalgharaghtakamminarronnkonnbronntonnerronntuonnthunntrovarrhounawnskawntoohoohoordenenthurnuk"
  dup echo$ cr
  circlesort echo$ cr


#lang racket
(define (circle-sort v0 [<? <])
  (define v (vector-copy v0))

  (define (swap-if l r)
    (define v.l (vector-ref v l))
    (define v.r (vector-ref v r))
    (and (<? v.r v.l)
         (begin (vector-set! v l v.r) (vector-set! v r v.l) #t)))

  (define (inr-cs! L R)
    (cond
      [(>= L (- R 1)) #f] ; covers 0 or 1 vectors
      [else
       (define M (quotient (+ L R) 2))
       (define I-moved?
         (for/or ([l (in-range L M)] [r (in-range (- R 1) L -1)])
           (swap-if l r)))
       (define M-moved? (and (odd? (- L R)) (> M 0) (swap-if (- M 1) M)))
       (define L-moved? (inr-cs! L M))
       (define R-moved? (inr-cs! M R))
       (or I-moved? L-moved? R-moved? M-moved?)]))

  (let loop () (when (inr-cs! 0 (vector-length v)) (loop)))
  v)

(define (sort-random-vector)
  (define v (build-vector (+ 2 (random 10)) (λ (i) (random 100))))
  (define v< (circle-sort v <))
  (define sorted? (apply <= (vector->list v<)))
  (printf "   ~.a\n-> ~.a [~a]\n\n" v v< sorted?))

(for ([_ 10]) (sort-random-vector))

(circle-sort '#("table" "chair" "cat" "sponge") string<?)


sub circlesort (@x, $beg, $end) {
    my $swaps = 0;
    if $beg < $end {
        my ($lo, $hi) = $beg, $end;
        repeat {
            if @x[$lo] after @x[$hi] {
                @x[$lo,$hi] .= reverse;
                ++$swaps;
            }
            ++$hi if --$hi == ++$lo
        } while $lo < $hi;
        $swaps += circlesort(@x, $beg, $hi);
        $swaps += circlesort(@x, $lo, $end);
    }
    $swaps;
}

say my @x = (-100..100).roll(20);
say @x while circlesort(@x, 0, @x.end);

say @x = <The quick brown fox jumps over the lazy dog.>;
say @x while circlesort(@x, 0, @x.end);


/*REXX program uses a  circle sort algorithm  to sort an array (or list) of numbers.    */
parse arg x                                      /*obtain optional arguments from the CL*/
if x='' | x=","  then x= 6 7 8 9 2 5 3 4 1       /*Not specified?  Then use the default.*/
call make_array  'before sort:'                  /*display the list and make an array.  */
call circleSort       #                          /*invoke the circle sort subroutine.   */
call make_list   ' after sort:'                  /*make a list and display it to console*/
exit                                             /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
circleSort:      do while  .circleSrt(1, arg(1), 0)\==0;     end;                   return
make_array: #= words(x);    do i=1 for #;  @.i= word(x, i);  end;  say arg(1)  x;   return
make_list:  y= @.1;         do j=2 for #-1;  y= y  @.j;      end;  say arg(1)  y;   return
.swap:      parse arg a,b;  parse  value  @.a @.b  with  @.b @.a;  swaps= swaps+1;  return
/*──────────────────────────────────────────────────────────────────────────────────────*/
.circleSrt: procedure expose @.;  parse arg LO,HI,swaps    /*obtain  LO & HI  arguments.*/
            if LO==HI  then return swaps                   /*1 element?  Done with sort.*/
            high= HI;      low= LO;     mid= (HI-LO) % 2   /*assign some indices.       */
                                                           /* [↓]  sort a section of #'s*/
                       do  while LO<HI                     /*sort within a section.     */
                       if @.LO>@.HI  then call .swap LO,HI /*are numbers out of order ? */
                       LO= LO + 1;        HI= HI - 1       /*add to LO;  shrink the HI. */
                       end   /*while*/                     /*just process one section.  */
            _= HI + 1                                      /*point to  HI  plus one.    */
            if LO==HI  &  @.LO>@._  then call .swap LO, _  /*numbers still out of order?*/
            swaps= .circleSrt(low,        low+mid,  swaps) /*sort the   lower  section. */
            swaps= .circleSrt(low+mid+1,  high,     swaps) /*  "   "   higher     "     */
            return swaps                                   /*the section sorting is done*/


# Project : Sorting Algorithms/Circle Sort

test = [-4, -1, 1, 0, 5, -7, -2, 4, -6, -3, 2, 6, 3, 7, -5]
while circlesort(1, len(test), 0) end
showarray(test)

func circlesort(lo, hi, swaps)
     if lo = hi
        return swaps
     ok
     high = hi
     low = lo
     mid = floor((hi-lo)/2)
     while lo < hi
           if test[lo] > test[hi]
               temp = test[lo]
               test[lo] = test[hi]
               test[hi] = temp
               swaps = swaps + 1
           ok
           lo = lo + 1
           hi = hi - 1
     end
     if lo = hi
        if test[lo] > test[hi+1]
           temp = test[lo]
           test[lo] = test[hi+1]
           test[hi + 1] = temp
           swaps = swaps + 1
        ok
     ok
     swaps = circlesort(low, low+mid, swaps)
     swaps = circlesort(low+mid+1 ,high, swaps)
     return swaps

func showarray(vect)
     see "["
     svect = ""
     for n = 1 to len(vect)
         svect = svect + vect[n] + ", "
     next
     svect = left(svect, len(svect) - 2)
     see svect
     see "]" + nl


class Array
  def circle_sort!
    while _circle_sort!(0, size-1) > 0
    end
    self
  end

  private
  def _circle_sort!(lo, hi, swaps=0)
    return swaps if lo == hi
    low, high = lo, hi
    mid = (lo + hi) / 2
    while lo < hi
      if self[lo] > self[hi]
        self[lo], self[hi] = self[hi], self[lo]
        swaps += 1
      end
      lo += 1
      hi -= 1
    end
    if lo == hi && self[lo] > self[hi+1]
      self[lo], self[hi+1] = self[hi+1], self[lo]
      swaps += 1
    end
    swaps + _circle_sort!(low, mid) + _circle_sort!(mid+1, high)
  end
end

ary = [6, 7, 8, 9, 2, 5, 3, 4, 1]
puts "before sort: #{ary}"
puts " after sort: #{ary.circle_sort!}"


fn _circle_sort<T: PartialOrd>(a: &mut [T], low: usize, high: usize, swaps: usize) -> usize {
    if low == high {
        return swaps;
    }
    let mut lo = low;
    let mut hi = high;
    let mid = (hi - lo) / 2;
    let mut s = swaps;
    while lo < hi {
        if a[lo] > a[hi] {
            a.swap(lo, hi);
            s += 1;
        }
        lo += 1;
        hi -= 1;
    }
    if lo == hi {
        if a[lo] > a[hi + 1] {
            a.swap(lo, hi + 1);
            s += 1;
        }
    }
    s = _circle_sort(a, low, low + mid, s);
    s = _circle_sort(a, low + mid + 1, high, s);
    return s;
}

fn circle_sort<T: PartialOrd>(a: &mut [T]) {
    let len = a.len();
    loop {
        if _circle_sort(a, 0, len - 1, 0) == 0 {
            break;
        }
    }
}

fn main() {
    let mut v = vec![10, 8, 4, 3, 1, 9, 0, 2, 7, 5, 6];
    println!("before: {:?}", v);
    circle_sort(&mut v);
    println!("after:  {:?}", v);
}


object CircleSort extends App {

  def sort(arr: Array[Int]): Array[Int] = {
    def circleSortR(arr: Array[Int], _lo: Int, _hi: Int, _numSwaps: Int): Int = {
      var lo = _lo
      var hi = _hi
      var numSwaps = _numSwaps

      def swap(arr: Array[Int], idx1: Int, idx2: Int): Unit = {
        val tmp = arr(idx1)
        arr(idx1) = arr(idx2)
        arr(idx2) = tmp
      }

      if (lo == hi) return numSwaps
      val (high, low) = (hi, lo)
      val mid = (hi - lo) / 2
      while ( lo < hi) {
        if (arr(lo) > arr(hi)) {
          swap(arr, lo, hi)
          numSwaps += 1
        }
        lo += 1
        hi -= 1
      }
      if (lo == hi && arr(lo) > arr(hi + 1)) {
        swap(arr, lo, hi + 1)
        numSwaps += 1
      }

      circleSortR(arr, low + mid + 1, high, circleSortR(arr, low, low + mid, numSwaps))
    }

    while (circleSortR(arr, 0, arr.length - 1, 0) != 0)()
    arr
  }

  println(sort(Array[Int](2, 14, 4, 6, 8, 1, 3, 5, 7, 11, 0, 13, 12, -1)).mkString(", "))

}


func circlesort(arr, beg=0, end=arr.end) {
    var swaps = 0
    if (beg < end) {
        var (lo, hi) = (beg, end)
        do {
            if (arr[lo] > arr[hi]) {
                arr.swap(lo, hi)
                ++swaps
            }
            ++hi if (--hi == ++lo)
        } while (lo < hi)
        swaps += circlesort(arr, beg, hi)
        swaps += circlesort(arr, lo, end)
    }
    return swaps
}

var numbers = %n(2 3 3 5 5 1 1 7 7 6 6 4 4 0 0)
do { say numbers } while circlesort(numbers)

var strs = ["John", "Kate", "Zerg", "Alice", "Joe", "Jane", "Alice"]
do { say strs } while circlesort(strs)


func circleSort<T: Comparable>(_ array: inout [T]) {
    func circSort(low: Int, high: Int, swaps: Int) -> Int {
        if low == high {
            return swaps
        }
        var lo = low
        var hi = high
        let mid = (hi - lo) / 2
        var s = swaps
        while lo < hi {
            if array[lo] > array[hi] {
                array.swapAt(lo, hi)
                s += 1
            }
            lo += 1
            hi -= 1
        }
        if lo == hi {
            if array[lo] > array[hi + 1] {
                array.swapAt(lo, hi + 1)
                s += 1
            }
        }
        s = circSort(low: low, high: low + mid, swaps: s)
        s = circSort(low: low + mid + 1, high: high, swaps: s)
        return s
    }
    while circSort(low: 0, high: array.count - 1, swaps: 0) != 0 {}
}

var array = [10, 8, 4, 3, 1, 9, 0, 2, 7, 5, 6]
print("before: \(array)")
circleSort(&array)
print(" after: \(array)")

var array2 = ["one", "two", "three", "four", "five", "six", "seven", "eight"]
print("before: \(array2)")
circleSort(&array2)
print(" after: \(array2)")


PRINT "Circle sort:"
  n = FUNC (_InitArray)
  PROC _ShowArray (n)
  PROC _Circlesort (n)
  PROC _ShowArray (n)
PRINT

END

_InnerCircle PARAM (2)
  LOCAL (3)
  [email protected] = [email protected]
  [email protected] = [email protected]
  [email protected] = 0

  IF [email protected] = [email protected] THEN RETURN (0)

  DO WHILE [email protected] < [email protected]
    IF @([email protected]) > @([email protected]) THEN PROC _Swap ([email protected], [email protected]) : [email protected] = [email protected] + 1
    [email protected] = [email protected] + 1
    [email protected] = [email protected] - 1
  LOOP

  [email protected] = [email protected] + FUNC (_InnerCircle ([email protected], [email protected]))
  [email protected] = [email protected] + FUNC (_InnerCircle ([email protected], [email protected]))
RETURN ([email protected])

_Circlesort PARAM(1)                   ' Circle sort
  DO WHILE FUNC (_InnerCircle (0, [email protected]))
  LOOP
RETURN

_Swap PARAM(2)                         ' Swap two array elements
  PUSH @([email protected])
  @([email protected]) = @([email protected])
  @([email protected]) = POP()
RETURN

_InitArray                             ' Init example array
  PUSH 4, 65, 2, -31, 0, 99, 2, 83, 782, 1

  FOR i = 0 TO 9
    @(i) = POP()
  NEXT

RETURN (i)

_ShowArray PARAM (1)                   ' Show array subroutine
  FOR i = 0 TO [email protected]
    PRINT @(i),
  NEXT

  PRINT
RETURN


fn circle_sort(mut a []int, l int, h int, s int) int {
    mut hi := h
    mut lo := l
    mut swaps := s
    if lo == hi {
        return swaps
    }
    high, low := hi, lo
    mid := (hi - lo) / 2
    for lo < hi {
        if a[lo] > a[hi] {
            a[lo], a[hi] = a[hi], a[lo]
            swaps++
        }
        lo++
        hi--
    }
    if lo == hi {
        if a[lo] > a[hi+1] {
            a[lo], a[hi+1] = a[hi+1], a[lo]
            swaps++
        }
    }
    swaps = circle_sort(mut a, low, low+mid, swaps)
    swaps = circle_sort(mut a, low+mid+1, high, swaps)
    return swaps
}

fn main() {
    aa := [
        [6, 7, 8, 9, 2, 5, 3, 4, 1],
        [2, 14, 4, 6, 8, 1, 3, 5, 7, 11, 0, 13, 12, -1],
    ]
    for a1 in aa {
        mut a:=a1.clone()
        println("Original: $a")
        for circle_sort(mut a, 0, a.len-1, 0) != 0 {
            // empty block
        }
        println("Sorted  : $a\n")
    }
}


var circleSort // recursive
circleSort = Fn.new { |a, lo, hi, swaps|
    if (lo == hi) return swaps
    var high = hi
    var low = lo
    var mid = ((hi-lo)/2).floor
    while (lo < hi) {
        if (a[lo] > a[hi]) {
            var t = a[lo]
            a[lo] = a[hi]
            a[hi] = t
            swaps = swaps + 1
        }
        lo = lo + 1
        hi = hi - 1
    }
    if (lo == hi) {
        if (a[lo] > a[hi+1]) {
            var t = a[lo]
            a[lo] = a[hi+1]
            a[hi+1] = t
            swaps = swaps + 1
        }
    }
    swaps = circleSort.call(a, low, low + mid, swaps)
    swaps = circleSort.call(a, low + mid + 1, high, swaps)
    return swaps
}

var as = [ [6, 7, 8, 9, 2, 5, 3, 4, 1], [2, 14, 4, 6, 8, 1, 3, 5, 7, 11, 0, 13, 12, -1] ]
for (a in as) {
    System.print("Before: %(a)")
    while (circleSort.call(a, 0, a.count-1, 0) != 0) {}
    System.print("After : %(a)")
    System.print()
}


fcn circleSort(list){
   csort:=fcn(list,lo,hi,swaps){
      if(lo==hi) return(swaps);
      high,low,mid:=hi,lo,(hi-lo)/2;
      while(lo<hi){
	 if(list[lo]>list[hi]){
	    list.swap(lo,hi);
	    swaps+=1;
	 }
	 lo+=1; hi-=1;
      }
      if(lo==hi)
	 if (list[lo]>list[hi+1]){
	    list.swap(lo,hi+1);
	    swaps+=1;
	 }
      swaps=self.fcn(list,low,low + mid,swaps);
      swaps=self.fcn(list,low + mid + 1,high,swaps);
      return(swaps);
   };
   list.println();
   while(csort(list,0,list.len()-1,0)){ list.println() }
   list
}


   10 DIM a(100): DIM s(32): RANDOMIZE : LET p=1: GO SUB 3000: GO SUB 2000: GO SUB 4000
   20 STOP
 1000 IF b=e THEN RETURN
 1010 LET s(p)=b: LET s(p+1)=e
 1020 IF a(s(p))>a(e) THEN LET t=a(s(p)): LET a(s(p))=a(e): LET a(e)=t: LET c=1
 1030 LET s(p)=s(p)+1: LET e=e-1: IF s(p)<e THEN GO TO 1020
 1040 LET p=p+2: GO SUB 1000: LET b=s(p-2): LET e=s(p-1): GO SUB 1000: LET p=p-2: RETURN
 2000 PRINT "*";: LET b=1: LET e=100: LET c=0: GO SUB 1000: IF c>0 THEN GO TO 2000
 2010 CLS : RETURN
 3000 FOR x=1 TO 100: LET a(x)=RND: NEXT x: RETURN
 4000 FOR x=1 TO 100: PRINT x,a(x): NEXT x: RETURN


F is_sorted(data)
   R all((0 .< data.len - 1).map(i -> @data[i] <= @data[i + 1]))

F bogosort(&data)
   L !is_sorted(data)
      random:shuffle(&data)

V arr = [2, 1, 3]
bogosort(&arr)
print(arr)


/* ARM assembly AARCH64 Raspberry PI 3B */
/*  program bogosort64.s   */

/*******************************************/
/* Constantes file                         */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
/*********************************/
/* Initialized data              */
/*********************************/
.data
sMessResult:      .asciz "Value  : @ \n"
szCarriageReturn: .asciz "\n"

.align 4
qGraine:  .quad 123456
TableNumber:       .quad   1,2,3,4,5,6,7,8,9,10
                   .equ NBELEMENTS, (. - TableNumber) / 8

/*********************************/
/* UnInitialized data            */
/*********************************/
.bss
sZoneConv:          .skip 24
/*********************************/
/*  code section                 */
/*********************************/
.text
.global main
main:                                           // entry of program

1:
    ldr x0,qAdrTableNumber                      // address number table
    mov x1,#NBELEMENTS                          // number of élements
    bl knuthShuffle
                                                // table  display elements
    ldr x0,qAdrTableNumber                      // address number table
    mov x1,#NBELEMENTS                          // number of élements
    bl displayTable

    ldr x0,qAdrTableNumber                      // address number table
    mov x1,#NBELEMENTS                          // number of élements
    bl isSorted                                 // control sort
    cmp x0,#1                                   // sorted ?
    bne 1b                                      // no -> loop

100:                                            // standard end of the program
    mov x0, #0                                  // return code
    mov x8, #EXIT                               // request to exit program
    svc #0                                      // perform the system call

qAdrszCarriageReturn:     .quad szCarriageReturn
qAdrsMessResult:          .quad sMessResult
qAdrTableNumber:          .quad TableNumber

/******************************************************************/
/*     control sorted table                                   */
/******************************************************************/
/* x0 contains the address of table */
/* x1 contains the number of elements  > 0  */
/* x0 return 0  if not sorted   1  if sorted */
isSorted:
    stp x2,lr,[sp,-16]!          // save  registers
    stp x3,x4,[sp,-16]!          // save  registers
    mov x2,#0
    ldr x4,[x0,x2,lsl #3]        // load A[0]
1:
    add x2,x2,#1
    cmp x2,x1                    // end ?
    bge 99f
    ldr x3,[x0,x2, lsl #3]       // load A[i]
    cmp x3,x4                    // compare A[i],A[i-1]
    blt 98f                      // smaller -> error -> return
    mov x4,x3                    // no -> A[i-1] = A[i]
    b 1b                         // and loop
98:
    mov x0,#0                    // error
    b 100f
99:
    mov x0,#1                    // ok -> return
100:
    ldp x2,x3,[sp],16            // restaur  2 registers
    ldp x1,lr,[sp],16            // restaur  2 registers
    ret                          // return to address lr x30
/******************************************************************/
/*      Display table elements                                */
/******************************************************************/
/* x0 contains the address of table */
/* x1 contains elements number  */
displayTable:
    stp x1,lr,[sp,-16]!          // save  registers
    stp x2,x3,[sp,-16]!          // save  registers
    mov x2,x0                    // table address
    mov x4,x1                    // elements number
    mov x3,#0
1:                               // loop display table
    ldr x0,[x2,x3,lsl #3]
    ldr x1,qAdrsZoneConv
    bl conversion10              // décimal conversion
    ldr x0,qAdrsMessResult
    ldr x1,qAdrsZoneConv         // insert conversion
    bl strInsertAtCharInc
    bl affichageMess             // display message
    add x3,x3,#1
    cmp x3,x4                    // end ?
    blt 1b                       // no -> loop
    ldr x0,qAdrszCarriageReturn
    bl affichageMess
100:
    ldp x2,x3,[sp],16            // restaur  2 registers
    ldp x1,lr,[sp],16            // restaur  2 registers
    ret                          // return to address lr x30
qAdrsZoneConv:           .quad sZoneConv
/******************************************************************/
/*     shuffle game                                       */
/******************************************************************/
/* x0 contains boxs address           */
/* x1 contains elements number        */
knuthShuffle:
    stp x1,lr,[sp,-16]!            // save  registers
    stp x2,x3,[sp,-16]!            // save  registers
    stp x4,x5,[sp,-16]!            // save  registers
    mov x5,x0                      // save table address
    mov x2,#0                      // start index
1:
    mov x0,x2                      // generate aleas
    bl genereraleas
    ldr x3,[x5,x2,lsl #3]          // swap number on the table
    ldr x4,[x5,x0,lsl #3]
    str x4,[x5,x2,lsl #3]
    str x3,[x5,x0,lsl #3]
    add x2,x2,1                                         // next number
    cmp x2,x1                                         // end ?
    blt 1b                                            // no -> loop

100:
    ldp x4,x5,[sp],16              // restaur  2 registers
    ldp x2,x3,[sp],16              // restaur  2 registers
    ldp x1,lr,[sp],16              // restaur  2 registers
    ret                            // return to address lr x30
/***************************************************/
/*   Generation random number                  */
/***************************************************/
/* x0 contains limit  */
genereraleas:
    stp x1,lr,[sp,-16]!            // save  registers
    stp x2,x3,[sp,-16]!            // save  registers
    ldr x1,qAdrqGraine
    ldr x2,[x1]
    ldr x3,qNbDep1
    mul x2,x3,x2
    ldr x3,qNbDep2
    add x2,x2,x3
    str x2,[x1]                    // maj de la graine pour l appel suivant
    cmp x0,#0
    beq 100f
    udiv x3,x2,x0
    msub x0,x3,x0,x2               // résult = remainder

100:                               // end function
    ldp x2,x3,[sp],16              // restaur  2 registers
    ldp x1,lr,[sp],16              // restaur  2 registers
    ret                            // return to address lr x30
qAdrqGraine: .quad qGraine
qNbDep1:     .quad 0x0019660d
qNbDep2:     .quad 0x3c6ef35f
/********************************************************/
/*        File Include fonctions                        */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"


PROC PrintArray(INT ARRAY a INT size)
  INT i

  Put('[)
  FOR i=0 TO size-1
  DO
    IF i>0 THEN Put(' ) FI
    PrintI(a(i))
  OD
  Put(']) PutE()
RETURN

PROC KnuthShuffle(INT ARRAY tab BYTE size)
  BYTE i,j
  INT tmp

  i=size-1
  WHILE i>0
  DO
    j=Rand(i+1)
    tmp=tab(i)
    tab(i)=tab(j)
    tab(j)=tmp
    i==-1
  OD
RETURN

BYTE FUNC IsSorted(INT ARRAY tab BYTE size)
  BYTE i

  IF size<2 THEN
    RETURN (1)
  FI
  FOR i=0 TO size-2
  DO
    IF tab(i)>tab(i+1) THEN
      RETURN (0)
    FI
  OD
RETURN (1)

PROC BogoSort(INT ARRAY a INT size)
  WHILE IsSorted(a,size)=0
  DO
    KnuthShuffle(a,size)
  OD
RETURN

PROC Test(INT ARRAY a INT size)
  PrintE("Array before sort:")
  PrintArray(a,size)
  BogoSort(a,size)
  PrintE("Array after sort:")
  PrintArray(a,size)
  PutE()
RETURN

PROC Main()
  INT ARRAY
    a(10)=[1 4 65535 0 7 4 20 65530],
    b(21)=[3 2 1 0 65535 65534 65533],
    c(8)=[101 102 103 104 105 106 107 108],
    d(12)=[1 65535 1 65535 1 65535 1
      65535 1 65535 1 65535]

  Test(a,8)
  Test(b,7)
  Test(c,8)
  Test(d,12)
RETURN


public function bogoSort(arr:Array):Array
{
    while (!sorted(arr))
    {
        shuffle(arr);
    }

    return arr;
}

public function shuffle(arr:Array):void
{
    for (var i:int = 0; i < arr.length; i++)
    {
        var rand:int = Math.floor(Math.random() * arr.length);
        var tmp:* = arr[i];
        arr[i] = arr[rand];
        arr[rand] = tmp;
    }
}

public function sorted(arr:Array):Boolean
{
    var last:int = arr[0];

    for (var i:int = 1; i < arr.length; i++)
    {
        if (arr[i] < last)
        {
            return false;
        }

        last = arr[i];
    }

    return true;
}


with Ada.Text_IO;  use Ada.Text_IO;
with Ada.Numerics.Discrete_Random;

procedure Test_Bogosort is
   generic
      type Ordered is private;
      type List is array (Positive range <>) of Ordered;
      with function "<" (L, R : Ordered) return Boolean is <>;
   procedure Bogosort (Data : in out List);

   procedure Bogosort (Data : in out List) is
      function Sorted return Boolean is
      begin
         for I in Data'First..Data'Last - 1 loop
            if not (Data (I) < Data (I + 1)) then
               return False;
            end if;
         end loop;
         return True;
      end Sorted;
      subtype Index is Integer range Data'Range;
      package Dices is new Ada.Numerics.Discrete_Random (Index);
      use Dices;
      Dice : Generator;
      procedure Shuffle is
         J    : Index;
         Temp : Ordered;
      begin
         for I in Data'Range loop
            J := Random (Dice);
            Temp := Data (I);
            Data (I) := Data (J);
            Data (J) := Temp;
         end loop;
      end Shuffle;
   begin
      while not Sorted loop
         Shuffle;
      end loop;
   end Bogosort;

   type List is array (Positive range <>) of Integer;
   procedure Integer_Bogosort is new Bogosort (Integer, List);
   Sequence : List := (7,6,3,9);
begin
   Integer_Bogosort (Sequence);
   for I in Sequence'Range loop
      Put (Integer'Image (Sequence (I)));
   end loop;
end Test_Bogosort;


MODE TYPE = INT;

PROC random shuffle = (REF[]TYPE l)VOID: (
    INT range = UPB l - LWB l + 1;
    FOR index FROM LWB l TO UPB l DO
        TYPE tmp := l[index];
        INT other := ENTIER (LWB l + random * range);
        l[index] := l[other];
        l[other] := tmp
    OD
);

PROC in order = (REF[]TYPE l)BOOL: (
    IF LWB l >= UPB l THEN
        TRUE
    ELSE
        TYPE last := l[LWB l];
        FOR index FROM LWB l + 1 TO UPB l DO
            IF l[index] < last THEN
                GO TO return false
            FI;
            last := l[index]
        OD;
        TRUE EXIT
        return false: FALSE
    FI
);

PROC bogo sort = (REF[]TYPE l)REF[]TYPE: (
    WHILE NOT in order(l) DO
        random shuffle(l)
    OD;
    l
);

[6]TYPE sample := (61, 52, 63, 94, 46, 18);
print((bogo sort(sample), new line))


/* ARM assembly Raspberry PI  */
/*  program bogosort.s   */

/************************************/
/* Constantes                       */
/************************************/
.equ STDOUT, 1     @ Linux output console
.equ EXIT,   1     @ Linux syscall
.equ WRITE,  4     @ Linux syscall
/*********************************/
/* Initialized data              */
/*********************************/
.data
sMessResult:      .ascii "Value  : "
sMessValeur:       .fill 11, 1, ' '            @ size => 11
szCarriageReturn: .asciz "\n"

.align 4
iGraine:  .int 123456
.equ NBELEMENTS,      6
TableNumber:	     .int   1,2,3,4,5,6,7,8,9,10

/*********************************/
/* UnInitialized data            */
/*********************************/
.bss
/*********************************/
/*  code section                 */
/*********************************/
.text
.global main
main:                                           @ entry of program

1:
    ldr r0,iAdrTableNumber                      @ address number table
    mov r1,#NBELEMENTS                          @ number of élements
    bl knuthShuffle

    @ table  display elements
    ldr r2,iAdrTableNumber
    mov r3,#0
2:                                              @ loop display table
    ldr r0,[r2,r3,lsl #2]
    ldr r1,iAdrsMessValeur                      @ display value
    bl conversion10                             @ call function
    ldr r0,iAdrsMessResult
    bl affichageMess                            @ display message
    add r3,#1
    cmp r3,#NBELEMENTS - 1
    ble 2b
    ldr r0,iAdrszCarriageReturn
    bl affichageMess

    ldr r0,iAdrTableNumber                      @ address number table
    mov r1,#NBELEMENTS                          @ number of élements
    bl isSorted                                 @ control sort
    cmp r0,#1                                   @ sorted ?
    bne 1b                                      @ no -> loop

100:                                            @ standard end of the program
    mov r0, #0                                  @ return code
    mov r7, #EXIT                               @ request to exit program
    svc #0                                      @ perform the system call

iAdrsMessValeur:          .int sMessValeur
iAdrszCarriageReturn:    .int szCarriageReturn
iAdrsMessResult:          .int sMessResult
iAdrTableNumber:          .int TableNumber
/******************************************************************/
/*     control sorted table                                   */
/******************************************************************/
/* r0 contains the address of table */
/* r1 contains the number of elements  > 0  */
/* r0 return 0  if not sorted   1  if sorted */
isSorted:
    push {r2-r4,lr}                                    @ save registers
    mov r2,#0
    ldr r4,[r0,r2,lsl #2]
1:
    add r2,#1
	cmp r2,r1
	movge r0,#1
	bge 100f
    ldr r3,[r0,r2, lsl #2]
	cmp r3,r4
	movlt r0,#0
	blt 100f
	mov r4,r3
	b 1b
100:
    pop {r2-r4,lr}
    bx lr                                              @ return
/******************************************************************/
/*     knuthShuffle Shuffle                                  */
/******************************************************************/
/* r0 contains the address of table */
/* r1 contains the number of elements */
knuthShuffle:
    push {r2-r5,lr}                                    @ save registers
    mov r5,r0                                          @ save table address
    mov r2,#0                                          @ start index
1:
    mov r0,r2                                          @ generate aleas
    bl genereraleas
    ldr r3,[r5,r2,lsl #2]                              @ swap number on the table
    ldr r4,[r5,r0,lsl #2]
    str r4,[r5,r2,lsl #2]
    str r3,[r5,r0,lsl #2]
    add r2,#1                                          @ next number
    cmp r2,r1                                          @ end ?
    blt 1b                                             @ no -> loop

100:
    pop {r2-r5,lr}
    bx lr                                              @ return

/******************************************************************/
/*     display text with size calculation                         */
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
    push {r0,r1,r2,r7,lr}                          @ save  registres
    mov r2,#0                                      @ counter length
1:                                                 @ loop length calculation
    ldrb r1,[r0,r2]                                @ read octet start position + index
    cmp r1,#0                                      @ if 0 its over
    addne r2,r2,#1                                 @ else add 1 in the length
    bne 1b                                         @ and loop
                                                   @ so here r2 contains the length of the message
    mov r1,r0                                      @ address message in r1
    mov r0,#STDOUT                                 @ code to write to the standard output Linux
    mov r7, #WRITE                                 @ code call system "write"
    svc #0                                         @ call systeme
    pop {r0,r1,r2,r7,lr}                           @ restaur des  2 registres */
    bx lr                                          @ return
/******************************************************************/
/*     Converting a register to a decimal unsigned                */
/******************************************************************/
/* r0 contains value and r1 address area   */
/* r0 return size of result (no zero final in area) */
/* area size => 11 bytes          */
.equ LGZONECAL,   10
conversion10:
    push {r1-r4,lr}                                 @ save registers
    mov r3,r1
    mov r2,#LGZONECAL

1:	                                            @ start loop
    bl divisionpar10U                               @ unsigned  r0 <- dividende. quotient ->r0 reste -> r1
    add r1,#48                                      @ digit
    strb r1,[r3,r2]                                 @ store digit on area
    cmp r0,#0                                       @ stop if quotient = 0
    subne r2,#1                                     @ else previous position
    bne 1b	                                    @ and loop
                                                    @ and move digit from left of area
    mov r4,#0
2:
    ldrb r1,[r3,r2]
    strb r1,[r3,r4]
    add r2,#1
    add r4,#1
    cmp r2,#LGZONECAL
    ble 2b
                                                      @ and move spaces in end on area
    mov r0,r4                                         @ result length
    mov r1,#' '                                       @ space
3:
    strb r1,[r3,r4]                                   @ store space in area
    add r4,#1                                         @ next position
    cmp r4,#LGZONECAL
    ble 3b                                            @ loop if r4 <= area size

100:
    pop {r1-r4,lr}                                    @ restaur registres
    bx lr                                             @return

/***************************************************/
/*   division par 10   unsigned                    */
/***************************************************/
/* r0 dividende   */
/* r0 quotient */
/* r1 remainder  */
divisionpar10U:
    push {r2,r3,r4, lr}
    mov r4,r0                                          @ save value
    //mov r3,#0xCCCD                                   @ r3 <- magic_number lower  raspberry 3
    //movt r3,#0xCCCC                                  @ r3 <- magic_number higter raspberry 3
    ldr r3,iMagicNumber                                @ r3 <- magic_number    raspberry 1 2
    umull r1, r2, r3, r0                               @ r1<- Lower32Bits(r1*r0) r2<- Upper32Bits(r1*r0)
    mov r0, r2, LSR #3                                 @ r2 <- r2 >> shift 3
    add r2,r0,r0, lsl #2                               @ r2 <- r0 * 5
    sub r1,r4,r2, lsl #1                               @ r1 <- r4 - (r2 * 2)  = r4 - (r0 * 10)
    pop {r2,r3,r4,lr}
    bx lr                                              @ leave function
iMagicNumber:  	.int 0xCCCCCCCD
/***************************************************/
/*   Generation random number                  */
/***************************************************/
/* r0 contains limit  */
genereraleas:
    push {r1-r4,lr}                                    @ save registers
    ldr r4,iAdriGraine
    ldr r2,[r4]
    ldr r3,iNbDep1
    mul r2,r3,r2
    ldr r3,iNbDep1
    add r2,r2,r3
    str r2,[r4]                                        @ maj de la graine pour l appel suivant
    cmp r0,#0
    beq 100f
    mov r1,r0                                          @ divisor
    mov r0,r2                                          @ dividende
    bl division
    mov r0,r3                                          @ résult = remainder

100:                                                   @ end function
    pop {r1-r4,lr}                                     @ restaur registers
    bx lr                                              @ return
/*****************************************************/
iAdriGraine: .int iGraine
iNbDep1: .int 0x343FD
iNbDep2: .int 0x269EC3
/***************************************************/
/* integer division unsigned                       */
/***************************************************/
division:
    /* r0 contains dividend */
    /* r1 contains divisor */
    /* r2 returns quotient */
    /* r3 returns remainder */
    push {r4, lr}
    mov r2, #0                                         @ init quotient
    mov r3, #0                                         @ init remainder
    mov r4, #32                                        @ init counter bits
    b 2f
1:                                                     @ loop
    movs r0, r0, LSL #1                                @ r0 <- r0 << 1 updating cpsr (sets C if 31st bit of r0 was 1)
    adc r3, r3, r3                                     @ r3 <- r3 + r3 + C. This is equivalent to r3 ? (r3 << 1) + C
    cmp r3, r1                                         @ compute r3 - r1 and update cpsr
    subhs r3, r3, r1                                   @ if r3 >= r1 (C=1) then r3 <- r3 - r1
    adc r2, r2, r2                                     @ r2 <- r2 + r2 + C. This is equivalent to r2 <- (r2 << 1) + C
2:
    subs r4, r4, #1                                    @ r4 <- r4 - 1
    bpl 1b                                             @ if r4 >= 0 (N=0) then loop
    pop {r4, lr}
    bx lr


bogoSort: function [items][
    a: new items
    while [not? sorted? a]-> shuffle 'a
    return a
]

print bogoSort [3 1 2 8 5 7 9 4 6]


MsgBox % Bogosort("987654")
MsgBox % Bogosort("319208")
MsgBox % Bogosort("fedcba")
MsgBox % Bogosort("gikhjl")

Bogosort(sequence) {
  While !Sorted(sequence)
    sequence := Shuffle(sequence)
  Return sequence
}

Sorted(sequence) {
  Loop, Parse, sequence
  {
    current := A_LoopField
    rest := SubStr(sequence, A_Index)
    Loop, Parse, rest
    {
      If (current > A_LoopField)
        Return false
    }
  }
  Return true
}

Shuffle(sequence) {
  Max := StrLen(sequence) + 1
  Loop % StrLen(sequence) {
    Random, Num, 1, % Max - A_Index
    Found .= SubStr(sequence, Num, 1)
    sequence := SubStr(sequence, 1, Num-1) . SubStr(sequence, Num+1)
  }
  Return Found
}


function randint(n)
{
  return int(n * rand())
}

function sorted(sa, sn)
{
  for(si=1; si < sn; si++) {
    if ( sa[si] > sa[si+1] ) return 0;
  }
  return 1
}

{
  line[NR] = $0
}
END { # sort it with bogo sort
  while ( sorted(line, NR) == 0 ) {
    for(i=1; i <= NR; i++) {
      r = randint(NR) + 1
      t = line[i]
      line[i] = line[r]
      line[r] = t
    }
  }
  #print it
  for(i=1; i <= NR; i++) {
    print line[i]
  }
}


      DIM test(9)
      test() = 4, 65, 2, 31, 0, 99, 2, 83, 782, 1

      shuffles% = 0
      WHILE NOT FNsorted(test())
        shuffles% += 1
        PROCshuffle(test())
      ENDWHILE
      PRINT ;shuffles% " shuffles required to sort "; DIM(test(),1)+1 " items."
      END

      DEF PROCshuffle(d())
      LOCAL I%
      FOR I% = DIM(d(),1)+1 TO 2 STEP -1
        SWAP d(I%-1), d(RND(I%)-1)
      NEXT
      ENDPROC

      DEF FNsorted(d())
      LOCAL I%
      FOR I% = 1 TO DIM(d(),1)
        IF d(I%) < d(I%-1) THEN = FALSE
      NEXT
      = TRUE


bogosort = { list |
	sorted = list.sort #Kinda cheating here
	while { list != sorted } { list.shuffle! }
	list
}

p bogosort [15 6 2 9 1 3 41 19]


#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

bool is_sorted(int *a, int n)
{
  while ( --n >= 1 ) {
    if ( a[n] < a[n-1] ) return false;
  }
  return true;
}

void shuffle(int *a, int n)
{
  int i, t, r;
  for(i=0; i < n; i++) {
    t = a[i];
    r = rand() % n;
    a[i] = a[r];
    a[r] = t;
  }
}

void bogosort(int *a, int n)
{
  while ( !is_sorted(a, n) ) shuffle(a, n);
}

int main()
{
  int numbers[] = { 1, 10, 9,  7, 3, 0 };
  int i;

  bogosort(numbers, 6);
  for (i=0; i < 6; i++) printf("%d ", numbers[i]);
  printf("\n");
}


using System;
using System.Collections.Generic;

namespace RosettaCode.BogoSort
{
    public static class BogoSorter
    {
        public static void Sort<T>(List<T> list) where T:IComparable
        {
            while (!list.isSorted())
            {
                list.Shuffle();
            }
        }

        private static bool isSorted<T>(this IList<T> list) where T:IComparable
        {
            if(list.Count<=1)
                return true;
            for (int i = 1 ; i < list.Count; i++)
                if(list[i].CompareTo(list[i-1])<0) return false;
            return true;
        }

        private static void Shuffle<T>(this IList<T> list)
        {
            Random rand = new Random();
            for (int i = 0; i < list.Count; i++)
            {
                int swapIndex = rand.Next(list.Count);
                T temp = list[swapIndex];
                list[swapIndex] = list[i];
                list[i] = temp;
            }
        }
    }

    class TestProgram
    {
        static void Main()
        {
            List<int> testList = new List<int> { 3, 4, 1, 8, 7, 4, -2 };
            BogoSorter.Sort(testList);
            foreach (int i in testList) Console.Write(i + " ");
        }

    }
}


(defn in-order? [order xs]
  (or (empty? xs)
      (apply order xs)))

(defn bogosort [order xs]
  (if (in-order? order xs) xs
    (recur order (shuffle xs))))

(println (bogosort < [7 5 12 1 4 2 23 18]))


identification division.
program-id. bogo-sort-program.
data division.
working-storage section.
01  array-to-sort.
    05 item-table.
        10 item          pic 999
            occurs 10 times.
01  randomization.
    05 random-seed       pic 9(8).
    05 random-index      pic 9.
01  flags-counters-etc.
    05 array-index       pic 99.
    05 adjusted-index    pic 99.
    05 temporary-storage pic 999.
    05 shuffles          pic 9(8)
        value zero.
    05 sorted            pic 9.
01  numbers-without-leading-zeros.
    05 item-no-zeros     pic z(4).
    05 shuffles-no-zeros pic z(8).
procedure division.
control-paragraph.
    accept random-seed from time.
    move function random(random-seed) to item(1).
    perform random-item-paragraph varying array-index from 2 by 1
    until array-index is greater than 10.
    display 'BEFORE SORT:' with no advancing.
    perform show-array-paragraph varying array-index from 1 by 1
    until array-index is greater than 10.
    display ''.
    perform shuffle-paragraph through is-it-sorted-paragraph
    until sorted is equal to 1.
    display 'AFTER SORT: ' with no advancing.
    perform show-array-paragraph varying array-index from 1 by 1
    until array-index is greater than 10.
    display ''.
    move shuffles to shuffles-no-zeros.
    display shuffles-no-zeros ' SHUFFLES PERFORMED.'
    stop run.
random-item-paragraph.
    move function random to item(array-index).
show-array-paragraph.
    move item(array-index) to item-no-zeros.
    display item-no-zeros with no advancing.
shuffle-paragraph.
    perform shuffle-items-paragraph,
    varying array-index from 1 by 1
    until array-index is greater than 10.
    add 1 to shuffles.
is-it-sorted-paragraph.
    move 1 to sorted.
    perform item-in-order-paragraph varying array-index from 1 by 1,
    until sorted is equal to zero
    or array-index is equal to 10.
shuffle-items-paragraph.
    move function random to random-index.
    add 1 to random-index giving adjusted-index.
    move item(array-index) to temporary-storage.
    move item(adjusted-index) to item(array-index).
    move temporary-storage to item(adjusted-index).
item-in-order-paragraph.
    add 1 to array-index giving adjusted-index.
    if item(array-index) is greater than item(adjusted-index)
    then move zero to sorted.


(defun nshuffle (sequence)
  (loop for i from (length sequence) downto 2
        do (rotatef (elt sequence (random i))
                    (elt sequence (1- i ))))
  sequence)

(defun sortedp (list predicate)
  (every predicate list (rest list)))

(defun bogosort (list predicate)
  (do ((list list (nshuffle list)))
      ((sortedp list predicate) list)))


def knuthShuffle(items : Array)
    i = items.size-1
    while i > 1
        j = Random.rand(0..i)
        items.swap(i, j)

        i -= 1
    end
end

def sorted?(items : Array)
    prev = items[0]
    items.each do |item|
        if item < prev
            return false
        end
        prev = item
    end
    return true
end

def bogoSort(items : Array)
    while !sorted?(items)
        knuthShuffle(items)
    end
end


import std.stdio, std.algorithm, std.random;

void bogoSort(T)(T[] data) {
    while (!isSorted(data))
        randomShuffle(data);
}

void main() {
    auto array = [2, 7, 41, 11, 3, 1, 6, 5, 8];
    bogoSort(array);
    writeln(array);
}


def isSorted(list) {
    if (list.size() == 0) { return true }
    var a := list[0]
    for i in 1..!(list.size()) {
        var b := list[i]
        if (a > b) { return false }
        a := b
    }
    return true
}

def bogosort(list, random) {
    while (!isSorted(list)) {
        shuffle(list, random)
    }
}


class
	BOGO_SORT

feature

	bogo_sort (ar: ARRAY [INTEGER]): ARRAY [INTEGER]
			-- Sorted array in ascending order.
		do
			from
			until
				is_sorted (ar) = True
			loop
				Result := shuffel (ar)
			end
		end

feature {NONE}

	is_sorted (ar: ARRAY [INTEGER]): BOOLEAN
			-- Is 'ar' sorted in ascending order?
		require
			not_void: ar /= Void
		local
			i: INTEGER
		do
			Result := True
			from
				i := 1 + 1
			invariant
				i >= 1 + 1 and i <= ar.count + 1
			until
				i > ar.count
			loop
				Result := Result and ar [i - 1] <= ar [i]
				i := i + 1
			variant
				ar.count + 1 - i
			end
		end

	shuffle (ar: ARRAY [INTEGER]): ARRAY [INTEGER]
			-- Array containing the same elements as 'ar' in a shuffled order.
		require
			more_than_one_element: ar.count > 1
		local
			count, j, ith: INTEGER
			random: V_RANDOM
		do
			create random
			create Result.make_empty
			Result.deep_copy (ar)
			count := ar.count
			across
				1 |..| count as c
			loop
				j := random.bounded_item (c.item, count)
				ith := Result [c.item]
				Result [c.item] := Result [j]
				Result [j] := ith
				random.forth
			end
		ensure
			same_elements: across ar as a all Result.has (a.item) end
		end

end


import extensions;
import system'routines;

extension op
{
    bogoSorter()
    {
        var list := self;

        until (list.isAscendant())
        {
            list := list.randomize(list.Length)
        };

        ^ list
    }
}

public program()
{
    var list := new int[]{3, 4, 1, 8, 7, -2, 0};

    console.printLine("before:", list.asEnumerable());
    console.printLine("after :", list.bogoSorter().asEnumerable())
}


defmodule Sort do
  def bogo_sort(list) do
    if sorted?(list) do
      list
    else
      bogo_sort(Enum.shuffle(list))
    end
  end

  defp sorted?(list) when length(list)<=1, do: true
  defp sorted?([x, y | _]) when x>y, do: false
  defp sorted?([_, y | rest]), do: sorted?([y | rest])
end


function shuffle(sequence s)
    object temp
    integer j
    for i = length(s) to 1 by -1 do
        j = rand(i)
        if i != j then
            temp = s[i]
            s[i] = s[j]
            s[j] = temp
        end if
    end for
    return s
end function

function inOrder(sequence s)
    for i = 1 to length(s)-1 do
        if compare(s[i],s[i+1]) > 0 then
            return 0
        end if
    end for
    return 1
end function

function bogosort(sequence s)
    while not inOrder(s) do
        ? s
        s = shuffle(s)
    end while
    return s
end function

? bogosort(shuffle({1,2,3,4,5,6}))


V x = 77444
V y =   -12
V z =     0
(x, y, z) = tuple_sorted((x, y, z))
print(x‘ ’y‘ ’z)

V xs = ‘lions, tigers, and’
V ys = ‘bears, oh my!’
V zs = ‘(from the "Wizard of OZ")’
(xs, ys, zs) = sorted([xs, ys, zs])
print(xs"\n"ys"\n"zs)


USING: grouping kernel math random sequences ;

: sorted? ( seq -- ? ) 2 <clumps> [ first2 <= ] all? ;
: bogosort ( seq -- newseq ) [ dup sorted? ] [ randomize ] until ;


class Main
{
  Bool in_order (Int[] items)
  {
    (0..<(items.size-1)).toList.all |Int i -> Bool|
    {
      items[i] <= items[i+1]
    }
  }

  Int[] bogosort (Int[] items)
  {
    while (!in_order(items))
    {
      items.shuffle
    }
    return items
  }

  Void main ()
  {
    // example
    echo ("Sorting [3,4,2,1] gives " + bogosort ([3,4,2,1]))
  }
}


mov ax,6FFFh
mov bx,3456h
mov cx,0

;We'll consider these sorted when ax <= bx <= cx.

SortRegisters proc
cmp ax,bx
jbe continue
     ;if we got here, ax > bx. We don't know the relationship between bx and cx at this time.
     cmp ax,cx
     jbe swap_ax_and_bx
        ;if we got here, ax > bx, and bx > cx. Therefore all we need to do is swap ax and cx, and we're done.
        xchg ax,cx
        jmp endOfProc

swap ax_and_bx:
;if we got here, ax > bx, and ax <= cx. So all we have to do is swap ax and bx, and we're done
xchg ax,bx
jmp end  ;back to top

continue:  ;if we got here, ax <= bx.
cmp bx,cx
jbe end
          ;if we got here, ax <= bx, and bx > cx. Therefore all we need to do is swap bx and cx, and we're done.
          xchg bx,cx

endOfProc: ;if we got here, ax <= bx, and bx <= cx. Therefore, ax <= bx <=cx and we are done.
;

SortRegisters endp


with Ada.Text_IO;
with Ada.Strings.Unbounded;

procedure Sort_Three is

   generic
      type Element_Type is private;
      with function "<" (Left, Right : in Element_Type) return Boolean;
   procedure Generic_Sort (X, Y, Z : in out Element_Type);

   procedure Generic_Sort (X, Y, Z : in out Element_Type)
   is
      procedure Swap (Left, Right : in out Element_Type) is
         T : constant Element_Type := Left;
      begin
         Left := Right;
         Right := T;
      end Swap;
   begin
      if Y < X then Swap (X, Y); end if;
      if Z < Y then Swap (Y, Z); end if;
      if Y < X then Swap (X, Y); end if;
   end Generic_Sort;

   procedure Test_Unbounded_Sort is
      use Ada.Text_IO;
      use Ada.Strings.Unbounded;

      X : Unbounded_String := To_Unbounded_String ("lions, tigers, and");
      Y : Unbounded_String := To_Unbounded_String ("bears, oh my!");
      Z : Unbounded_String := To_Unbounded_String ("(from the ""Wizard of OZ"")");

      procedure Sort is
         new Generic_Sort (Unbounded_String, "<");
   begin
      Sort (X, Y, Z);
      Put_Line (To_String (X));
      Put_Line (To_String (Y));
      Put_Line (To_String (Z));
      New_Line;
   End Test_Unbounded_Sort;

   procedure Test_Integer_Sort is

      use Ada.Text_IO;

      procedure Sort is
         new Generic_Sort (Integer, "<");

      X : Integer := 77444;
      Y : Integer :=   -12;
      Z : Integer :=     0;
   begin
      Sort (X, Y, Z);
      Put_Line (X'Image);
      Put_Line (Y'Image);
      Put_Line (Z'Image);
      New_Line;
   end Test_Integer_Sort;

begin
   Test_Unbounded_Sort;
   Test_Integer_Sort;
end Sort_Three;


MODULE BOGO
IMPLICIT NONE
CONTAINS
  FUNCTION Sorted(a)
    LOGICAL :: Sorted
    INTEGER, INTENT(IN) :: a(:)
    INTEGER :: i

    Sorted = .TRUE.
    DO i = 1, SIZE(a)-1
      IF(a(i) > a(i+1)) THEN
        Sorted = .FALSE.
        EXIT
      END IF
    END DO
  END FUNCTION Sorted

  SUBROUTINE SHUFFLE(a)
    INTEGER, INTENT(IN OUT) :: a(:)
    INTEGER :: i, rand, temp
    REAL :: x

    DO i = SIZE(a), 1, -1
       CALL RANDOM_NUMBER(x)
       rand = INT(x * i) + 1
       temp = a(rand)
       a(rand) = a(i)
       a(i) = temp
    END DO
  END SUBROUTINE
END MODULE

PROGRAM BOGOSORT

  USE BOGO
  IMPLICIT NONE
  INTEGER :: iter = 0
  INTEGER :: array(8) = (/2, 7, 5, 3, 4, 8, 6, 1/)
  LOGICAL :: s

  DO
    s = Sorted(array)
    IF (s) EXIT
    CALL SHUFFLE(array)
    iter = iter + 1
  END DO
  WRITE (*,*) "Array required", iter, " shuffles to sort"

END PROGRAM BOGOSORT


integer a, b, c;
index i;
text x, y, z;
record r;

x = "lions, tigers, and";
y = "bears, oh my!";
z = "(from the \"Wizard of OZ\")";

r.fit(x, x, y, y, z, z);

x = r.rf_pick;
y = r.rf_pick;
z = r.rf_pick;

o_form("~\n~\n~\n", x, y, z);

a = 77444;
b = -12;
c = 0;

i.fit(a, a, b, b, c, c);

a = i.if_pick;
b = i.if_pick;
c = i.if_pick;

o_form("~\n~\n~\n", a, b, c);


BEGIN
    # MODE that can hold integers and strings - would need to be extended to #
    # allow for other types                                                  #
    MODE INTORSTRING = UNION( INT, STRING );
    # returns TRUE if a is an INT, FALSE otherwise #
    OP   ISINT    = ( INTORSTRING a )BOOL:   CASE a IN (INT):      TRUE OUT FALSE ESAC;
    # returns TRUE if a is an INT, FALSE otherwise #
    OP   ISSTRING = ( INTORSTRING a )BOOL:   CASE a IN (STRING):   TRUE OUT FALSE ESAC;
    # returns the integer in a or 0 if a isn't an integer #
    OP   TOINT    = ( INTORSTRING a )INT:    CASE a IN (INT i):    i    OUT 0     ESAC;
    # returns the string in a or "" if a isn't a string #
    OP   TOSTRING = ( INTORSTRING a )STRING: CASE a IN (STRING s): s    OUT ""    ESAC;
    # returns TRUE if a < b, FALSE otherwise #
    # a and b must have the same type #
    PRIO LESSTHAN = 4;
    OP   LESSTHAN = ( INTORSTRING a, b )BOOL:
        IF  ISSTRING a AND ISSTRING b THEN
            # both strings #
            TOSTRING a < TOSTRING b
        ELIF ISINT a AND ISINT b THEN
            # both integers #
            TOINT a < TOINT b
        ELSE
            # different MODEs #
            FALSE
        FI # LESSTHAN # ;
    # exchanges the values of a and b #
    PRIO SWAP = 9;
    OP   SWAP = ( REF INTORSTRING a, b )VOID: BEGIN INTORSTRING t := a; a := b; b := t END;
    # sorts a, b and c #
    PROC sort 3 = ( REF INTORSTRING a, b, c )VOID:
    BEGIN
        IF b LESSTHAN a THEN a SWAP b FI;
        IF c LESSTHAN a THEN a SWAP c FI;
        IF c LESSTHAN b THEN b SWAP c FI
    END # sort 3 # ;

    # task test cases #
    INTORSTRING x, y, z;
    x := "lions, tigers, and";
    y := "bears, oh my!";
    z := "(from the ""Wizard of OZ"")";
    sort 3( x, y, z );
    print( ( x, newline, y, newline, z, newline ) );
    x := 77444;
    y := -12;
    z := 0;
    sort 3( x, y, z );
    print( ( x, newline, y, newline, z, newline ) )
END


sub shuffle( a() as long )
    dim as ulong n = ubound(a), i, j, k, m = ubound(a)*2
    dim as ulong tmp
    randomize timer
    for k=1 to m
        i=int(rnd*n)
        j=int(rnd*n)
        tmp = a(i)
        a(i) = a(j)
        a(j) = tmp
    next k
end sub

function inorder( a() as long ) as boolean
    dim as ulong i, n = ubound(a)
    for i = 0 to n-2
        if a(i)>a(i+1) then
            return false
        end if
    next i
    return true
end function

sub bogosort( a() as long )
    while not inorder(a())
        shuffle(a())
    wend
end sub

dim as long a(5) = {10, 1, 2, -6, 3}
dim as long i

bogosort(a())

for i=0 to ubound(a) - 1
    print a(i)
next i


Public Sub Main()
Dim sSorted As String = "123456789"                       'The desired outcome
Dim sTest, sChr As String                                 'Various strings
Dim iCounter As Integer                                   'Loop counter

Do
  Inc iCounter                                            'Increase counter value
  Repeat                                                  'Repeat
    sChr = Chr(Rand(49, 57))                              'Get a random number and convert it to a character e.g. 49="1"
    If Not InStr(sTest, sChr) Then sTest &= sChr          'If the random character is not in sTest then add it
  Until Len(sTest) = 9                                    'Loop until sTest has 9 characters
  Print sTest                                             'Print the string to test
  If sTest = sSorted Then Break                           'If sTest = sSorted then get out of the loop
  sTest = ""                                              'Empty sTest and try again
Loop

Print "Solved in " & Str(iCounter) & " loops"             'Print the result

End


set x to "lions, tigers, and"
set y to "bears, oh my!"
set z to "(from the \"Wizard of OZ\")"

if (x > y) then set {x, y} to {y, x}
if (y > z) then
    set {y, z} to {z, y}
    if (x > y) then set {x, y} to {y, x}
end if

return {x, y, z}


x: {lions, tigers, and}
y: {bears, oh my!}
z: {(from the "Wizard of OZ")}

print join.with:"\n" sort @[x y z]

x: 125
y: neg 2
z: pi

print sort @[x y z]


package main

import (
    "fmt"
    "math/rand"
    "sort"
    "time"
)

func main() {
    list := []int{31, 41, 59, 26, 53, 58, 97, 93, 23, 84}
    rand.Seed(time.Now().UnixNano())
    fmt.Println("unsorted:", list)
    temp := make([]int, len(list))
    copy(temp, list)
    for !sort.IntsAreSorted(temp) {
        for i, v := range rand.Perm(len(list)) {
            temp[i] = list[v]
        }
    }
    fmt.Println("sorted!  ", temp)
}


def bogosort = { list ->
    def n = list.size()
    while (n > 1 && (1..<n).any{ list[it-1] > list[it] }) {
        print '.'*n
        Collections.shuffle(list)
    }
    list
}


SortThreeVariables(ByRef x,ByRef y,ByRef z){
  obj := []
  for k, v in (var := StrSplit("x,y,z", ","))
    obj[%v%] := true
  for k, v in obj
    temp := var[A_Index], %temp% := k
}


get "libhdr"

// Sort 3 variables using a comparator.
// X, Y and Z are pointers.
let sort3(comp, x, y, z) be
$(  sort2(comp, x, y)
    sort2(comp, x, z)
    sort2(comp, y, z)
$)
and sort2(comp, x, y) be
    if comp(!x, !y) > 0
    $(  let t = !x
        !x := !y
        !y := t
    $)

// Integer and string comparators
let intcomp(x, y) = x - y
let strcomp(x, y) = valof
$(  for i=1 to min(x%0, y%0)
        unless x%i = y%i
            resultis intcomp(x%i, y%i)
    resultis intcomp(x%0, y%0)
$)
and min(x, y) = x < y -> x, y

// Run the function on both ints and strings
let start() be
$(  printAndSort(writen, intcomp, 7444, -12, 0)
    printAndSort(writes, strcomp,
        "lions, tigers, and",
        "bears, oh my!",
        "(from the *"Wizard of OZ*")")
$)

// Print the 3 values, sort them, and print them again
and printAndSort(printfn, comp, x, y, z) be
$(  print3(printfn, x, y, z) ; writes("*N")
    sort3(comp, @x, @y, @z)
    print3(printfn, x, y, z) ; writes("------*N")
$)

// Print 3 values given printing function
and print3(printfn, x, y, z) be
$(  writes("X = ") ; printfn(x) ; wrch('*N')
    writes("Y = ") ; printfn(y) ; wrch('*N')
    writes("Z = ") ; printfn(z) ; wrch('*N')
$)


#include<string.h>
#include<stdlib.h>
#include<stdio.h>

#define MAX 3

int main()
{
  char values[MAX][100],tempStr[100];
  int i,j,isString=0;
  double val[MAX],temp;

  for(i=0;i<MAX;i++){
    printf("Enter %d%s value : ",i+1,(i==0)?"st":((i==1)?"nd":"rd"));
    fgets(values[i],100,stdin);

    for(j=0;values[i][j]!=00;j++){
      if(((values[i][j]<'0' || values[i][j]>'9') && (values[i][j]!='.' ||values[i][j]!='-'||values[i][j]!='+'))
      ||((values[i][j]=='.' ||values[i][j]=='-'||values[i][j]=='+')&&(values[i][j+1]<'0' || values[i][j+1]>'9')))
        isString = 1;
    }
  }

  if(isString==0){
    for(i=0;i<MAX;i++)
      val[i] = atof(values[i]);
  }

  for(i=0;i<MAX-1;i++){
    for(j=i+1;j<MAX;j++){
      if(isString==0 && val[i]>val[j]){
        temp = val[j];
        val[j] = val[i];
        val[i] = temp;
      }

      else if(values[i][0]>values[j][0]){
        strcpy(tempStr,values[j]);
        strcpy(values[j],values[i]);
        strcpy(values[i],tempStr);
      }
    }
  }

  for(i=0;i<MAX;i++)
    isString==1?printf("%c = %s",'X'+i,values[i]):printf("%c = %lf",'X'+i,val[i]);

  return 0;
}


import System.Random
import Data.Array.IO
import Control.Monad

isSortedBy :: (a -> a -> Bool) -> [a] -> Bool
isSortedBy _ [] = True
isSortedBy f xs = all (uncurry f) . (zip <*> tail) $ xs

-- from http://www.haskell.org/haskellwiki/Random_shuffle
shuffle :: [a] -> IO [a]
shuffle xs = do
        ar <- newArray n xs
        forM [1..n] $ \i -> do
            j <- randomRIO (i,n)
            vi <- readArray ar i
            vj <- readArray ar j
            writeArray ar j vi
            return vj
  where
    n = length xs
    newArray :: Int -> [a] -> IO (IOArray Int a)
    newArray n xs =  newListArray (1,n) xs

bogosortBy :: (a -> a -> Bool) -> [a] -> IO [a]
bogosortBy f xs | isSortedBy f xs = return xs
                | otherwise       = shuffle xs >>= bogosortBy f

bogosort :: Ord a => [a] -> IO [a]
bogosort = bogosortBy (<)


using System;
public class Program
{
    public static void Main()
    {
        (int x, int y, int z) = (77444, -12, 0);

        //Sort directly:
        if (x > y) (x, y) = (y, x);
        if (x > z) (x, z) = (z, x);
        if (y > z) (y, z) = (z, y);
        Console.WriteLine((x, y, z));

        var (a, b, c) = (
            "lions, tigers, and",
            "bears, oh my!",
            "(from the 'Wizard of OZ')");

        //Sort with generic method:
        Sort(ref a, ref b, ref c);
        Console.WriteLine((a, b, c));
    }

    public static void Sort<T>(ref T a, ref T b, ref T c)
        where T : IComparable<T>
    {
        if (a.CompareTo(b) > 0) (a, b) = (b, a);
        if (a.CompareTo(c) > 0) (a, c) = (c, a);
        if (b.CompareTo(c) > 0) (b, c) = (c, b);
    }
}


#include <algorithm>
#include <iostream>
#include <string>
#include <vector>

template < class T >
void sort3( T& x, T& y, T& z) {
    std::vector<T> v{x, y, z};
    std::sort(v.begin(), v.end());
    x = v[0]; y = v[1]; z = v[2];
}
int main() {
    int xi = 77444, yi = -12, zi = 0;
    sort3( xi, yi, zi );
    std::cout << xi << "\n" << yi << "\n" << zi << "\n\n";

    std::string xs, ys, zs;
    xs = "lions, tigers, and";
    ys = "bears, oh my!";
    zs = "(from the \"Wizard of OZ\")";
    sort3( xs, ys, zs );
    std::cout << xs << "\n" << ys << "\n" << zs << "\n\n";

    float xf = 11.3f, yf = -9.7f, zf = 11.17f;
    sort3( xf, yf, zf );
    std::cout << xf << "\n" << yf << "\n" << zf << "\n\n";
}


procedure shuffle(l)
   repeat {
       !l :=: ?l
       suspend l
   }
end

procedure sorted(l)
   local i
   if (i := 2 to *l & l[i] >= l[i-1]) then return &fail else return 1
end

procedure main()
   local l
   l := [6,3,4,5,1]
   |( shuffle(l) & sorted(l)) \1 & every writes(" ",!l)
end


[ shuffle a n i j tmp;
  for(i = n - 1: i > 0: i--)
  {
    j = random(i + 1) - 1;

    tmp = a->j;
    a->j = a->i;
    a->i = tmp;
  }
];

[ is_sorted a n i;
  for(i = 0: i < n - 1: i++)
  {
    if(a->i > a->(i + 1)) rfalse;
  }

  rtrue;
];

[ bogosort a n;
  while(~~is_sorted(a, n))
  {
    shuffle(a, n);
  }
];


% Sort three variables.
% The variables must all be of the same type, and the type
% must implement the less-than comparator.
sort_three = proc [T: type] (x,y,z: T) returns (T,T,T)
             where T has lt: proctype (T,T) returns (bool)
    if y<x then x,y := y,x end
    if z<y then y,z := z,y end
    if y<x then x,y := y,z end
    return(x,y,z)
end sort_three

% Test it out on three values, when also given a type and a
% formatter.
example = proc [T: type] (x,y,z: T, fmt: proctype (T) returns (string))
          where T has lt: proctype (T,T) returns (bool)
    po: stream := stream$primary_output()

    % Print the variables
    stream$putl(po, "x=" || fmt(x)
                || " y=" || fmt(y)
                || " z=" || fmt(z))

    % Sort them
    x,y,z := sort_three[T](x,y,z)

    % Print them again
    stream$putl(po, "x=" || fmt(x)
                || " y=" || fmt(y)
                || " z=" || fmt(z)
                || "\n")
end example

% And then we also need formatters, since those are not standardized
% such as '<' is.
fmt_real = proc (n: real) returns (string)
    return(f_form(n,2,2))
end fmt_real

fmt_str = proc (s: string) returns (string)
    return( "'" || s || "'" )
end fmt_str

% Test it out on values of each type
start_up = proc ()
    example[int] (77444, -12, 0, int$unparse)
    example[real] (11.3, -9.7, 11.17, fmt_real)
    example[string] ("lions, tigers and", "bears, oh my!",
                    "(from the \"Wizard of Oz\")", fmt_str)
end start_up


       program-id. 3var.
       data division.
       working-storage section.
       1 n binary pic 9(4).
       1 num pic -(7)9.
       1 a1 pic x(32) value "lions, tigers, and".
       1 a2 pic x(32) value "bears, oh my!".
       1 a3 pic x(32) value "(from the ""Wizard of OZ"")".
       1 n1 pic x(8) value "77444".
       1 n2 pic x(8) value "-12".
       1 n3 pic x(8) value "0".
       1 alpha-table.
        2 alpha-entry occurs 3 pic x(32).
       1 numeric-table.
        2 numeric-entry occurs 3 pic s9(8).
       1 filler value "x = y = z = ".
        2 lead-in occurs 3 pic x(4).
       procedure division.
       begin.
           move a1 to alpha-entry (1)
           move a2 to alpha-entry (2)
           move a3 to alpha-entry (3)
           sort alpha-entry ascending alpha-entry
           perform varying n from 1 by 1
           until n > 3
               display lead-in (n) alpha-entry (n)
           end-perform

           display space

           compute numeric-entry (1) = function numval (n1)
           compute numeric-entry (2) = function numval (n2)
           compute numeric-entry (3) = function numval (n3)
           sort numeric-entry ascending numeric-entry
           perform varying n from 1 by 1
           until n > 3
               move numeric-entry (n) to num
               display lead-in (n) num
           end-perform

           stop run
           .
       end program 3var.


List do(
    isSorted := method(
        slice(1) foreach(i, x,
            if (x < at(i), return false)
        )
        return true;
    )

    bogoSortInPlace := method(
        while(isSorted not,
            shuffleInPlace()
        )
    )
)

lst := list(2, 1, 4, 3)
lst bogoSortInPlace println # ==> list(1, 2, 3, 4), hopefully :)


bogo=: monad define
  whilst.  +./ 2 >/\ Ry  do. Ry=. (A.~ [email protected][email protected]#) y  end. Ry
)


include "cowgol.coh";

# Sort 3 values
sub sort3(a: int32, b: int32, c: int32): (x: int32, y: int32, z: int32) is
    sub sort2(a: int32, b: int32): (x: int32, y: int32) is
        if a > b then
            x := b;
            y := a;
        else
            x := a;
            y := b;
        end if;
    end sub;

    x := a;
    y := b;
    z := c;
    (x, y) := sort2(x, y);
    (x, z) := sort2(x, z);
    (y, z) := sort2(y, z);
end sub;

# Print 3 values
sub print3(a: int32, b: int32, c: int32) is
    sub print1(a: int32) is
        var buf: uint8[10];
        [IToA(a, 10, &buf[0])] := 0;
        print(&buf[0]);
        print_char(' ');
    end sub;

    print1(a);
    print1(b);
    print1(c);
    print_nl();
end sub;

var x: int32 := 77444;
var y: int32 := -12;
var z: int32 := 0;

# Print 3 values before sorting
print3(x, y, z);

# Sort 3 values
(x, y, z) := sort3(x, y, z);

# Print 3 values after sorting
print3(x, y, z);


import std.stdio;

void main() {
    driver(77444, -12, 0);
    driver("lions, tigers, and", "bears, oh my!", "(from the \"Wizard of OZ\")");
}

void driver(T)(T x, T y, T z) {
    writeln("BEFORE: x=[", x, "]; y=[", y, "]; z=[", z, "]");
    sort3Var(x,y,z);
    writeln("AFTER: x=[", x, "]; y=[", y, "]; z=[", z, "]");
}

void sort3Var(T)(ref T x, ref T y, ref T z)
out {
    assert(x<=y);
    assert(x<=z);
    assert(y<=z);
}
body {
    import std.algorithm : swap;

    if (x < y) {
        if (z < x) {
            swap(x,z);
        }
    } else if (y < z) {
        swap(x,y);
    } else {
        swap(x,z);
    }
    if (z<y) {
        swap(y,z);
    }
}


public class BogoSort
{
	public static void main(String[] args)
	{
		//Enter array to be sorted here
		int[] arr={4,5,6,0,7,8,9,1,2,3};

		BogoSort now=new BogoSort();
		System.out.print("Unsorted: ");
		now.display1D(arr);

		now.bogo(arr);

		System.out.print("Sorted: ");
		now.display1D(arr);
	}
	void bogo(int[] arr)
	{
		//Keep a track of the number of shuffles
		int shuffle=1;
		for(;!isSorted(arr);shuffle++)
			shuffle(arr);
		//Boast
		System.out.println("This took "+shuffle+" shuffles.");
	}
	void shuffle(int[] arr)
	{
		//Standard Fisher-Yates shuffle algorithm
		int i=arr.length-1;
		while(i>0)
			swap(arr,i--,(int)(Math.random()*i));
	}
	void swap(int[] arr,int i,int j)
	{
		int temp=arr[i];
		arr[i]=arr[j];
		arr[j]=temp;
	}
	boolean isSorted(int[] arr)
	{

		for(int i=1;i<arr.length;i++)
			if(arr[i]<arr[i-1])
				return false;
		return true;
	}
	void display1D(int[] arr)
	{
		for(int i=0;i<arr.length;i++)
			System.out.print(arr[i]+" ");
		System.out.println();
	}

}


import extensions;

sortThree(ref object a, ref object b, ref object c)
{
    if (a > b) { exchange(ref a, ref b) };
    if (a > c) { exchange(ref a, ref c) };
    if (b > c) { exchange(ref b, ref c) }
}

public program()
{
    var x := 5;
    var y := 1;
    var z := 2;

    var a := "lions, tigers, and";
    var b := "bears, oh my!";
    var c := "(from the 'Wizard of OZ')";

    sortThree(ref x,ref y,ref z);
    sortThree(ref a,ref b,ref c);

    console.printLine(x,",",y,",",z);
    console.printLine(a,",",b,",",c)
}


x = 'lions, tigers, and'
y = 'bears, oh my!'
z = '(from the "Wizard of OZ")'

[x, y, z] = Enum.sort([x, y, z])
IO.puts "x = #{x}\ny = #{y}\nz = #{z}\n"

x = 77444
y = -12
z = 0

[x, y, z] = Enum.sort([x, y, z])
IO.puts "x = #{x}\ny = #{y}\nz = #{z}"


 let x = "lions, tigers, and"
 let y = "bears, oh my!"
 let z = """(from the "Wizard of OZ")"""
 List.iter (printfn "%s") (List.sort [x;y;z])


shuffle = function(v) {
    for(var j, x, i = v.length; i; j = Math.floor(Math.random() * i), x = v[--i], v[i] = v[j], v[j] = x);
    return v;
};

isSorted = function(v){
    for(var i=1; i<v.length; i++) {
        if (v[i-1] > v[i]) { return false; }
    }
    return true;
}

bogosort = function(v){
    var sorted = false;
    while(sorted == false){
        v = shuffle(v);
        sorted = isSorted(v);
    }
    return v;
}


USING: arrays io kernel prettyprint sequences sorting ;
IN: rosetta-code.sort-three

: sort3 ( b c a -- a b c ) 3array natural-sort first3 ;

"lions, tigers, and"
"bears, oh my!"
"(from the \"Wizard of OZ\")"
sort3 [ print ] [email protected]

77444 -12 0 sort3 [ . ] [email protected]


{ [s]waps two variables. (varref; varref) → () }
[
  b:  { loads the value at the top of the stack into b }
  a:  { loads the value at the top of the stack into a }

  a;; t:  { loads the value stored in the variable stored in a (hence the double dereference) into t }
  b;; a;:  { loads the value stored in the variable stored in b into the variable stored in a }
  t; b;:  { loads the value stored in t into the variable stored in b }
]s:

{ [p]rints the three variables. }
[
  "X = " x;. 10,
  "Y = " y;. 10,
  "Z = " z;. 10,
]p:

77444 x:
12_ y:
0 z:

p;!

{ if x > y, swap x and y }
x;y;> [xys;!] ?

{ if y > z, swap y and z }
y;z;> [yzs;!] ?

{ if x > y, swap x and y }
x;y;> [xys;!] ?

"After sorting:
"

p;!


#macro sort_three( x, y, z )
    if x>y then swap x, y
    if y>z then swap y, z
    if x>y then swap x, y
#endmacro

'demonstrate this for strings
dim as string x =  "lions, tigers, and"
dim as string y =  "bears, oh my!"
dim as string z =  "(from the ""Wizard of OZ"")"

sort_three(x,y,z)
print x
print y
print z : print

'demonstrate this for signed integers
dim as integer a = 77444
dim as integer b = -12
dim as integer c = 0

sort_three(a,b,c)
print a
print b
print c


function bogosort!(arr::AbstractVector)
    while !issorted(arr)
        shuffle!(arr)
    end
    return arr
end

v = rand(-10:10, 10)
println("# unordered: $v\n -> ordered: ", bogosort!(v))


// version 1.1.2

const val RAND_MAX = 32768 // big enough for this

val rand = java.util.Random()

fun isSorted(a: IntArray): Boolean {
    val n = a.size
    if (n < 2) return true
    for (i in 1 until n) {
        if (a[i] < a[i - 1]) return false
    }
    return true
}

fun shuffle(a: IntArray) {
    val n = a.size
    if (n < 2) return
    for (i in 0 until n) {
        val t = a[i]
        val r = rand.nextInt(RAND_MAX) % n
        a[i] = a[r]
        a[r] = t
    }
}

fun bogosort(a: IntArray) {
   while (!isSorted(a)) shuffle(a)
}

fun main(args: Array<String>) {
    val a = intArrayOf(1, 10, 9,  7, 3, 0)
    println("Before sorting : ${a.contentToString()}")
    bogosort(a)
    println("After sorting  : ${a.contentToString()}")
}


\ sort 3 integers
VARIABLE X  VARIABLE Y   VARIABLE Z

: [email protected]  ( --- n n n)  X @  Y @   Z @ ; \ read variables
: VARS!  ( n n n -- )  Z !  Y !   X ! ; \ store variables

: ?SWAP     ( a b -- a b)   \ conditional swap
            2DUP < IF SWAP THEN ;

: SORT3INTS ( a b c -- c b a)  ?SWAP >R  ?SWAP  R>  ?SWAP ;


      TYPE(MONGREL)
       INTEGER TYPEIS
       INTEGER VI
       REAL VF
       CHARACTER*(enuff) VC
       ...etc...
      END TYPE MONGREL
      TYPE (MONGREL) DOG


{$mode objFPC}

generic procedure sort<T>(var X, Y: T);
	procedure swap;
	var
		Z: T;
	begin
		Z := X;
		X := Y;
		Y := Z
	end;
begin
	if X > Y then
	begin
		swap
	end
end;

generic procedure sort<T>(var X, Y, Z: T);
begin
	specialize sort<T>(X, Y);
	specialize sort<T>(X, Z);
	specialize sort<T>(Y, Z)
end;

generic procedure print<T>(const X, Y, Z: T);
begin
	writeLn('X = ', X);
	writeLn('Y = ', Y);
	writeLn('Z = ', Z)
end;

{ === MAIN ============================================================= }
var
	A, B, C: string;
	I, J, K: integer;
	P, Q, R: real;
begin
	A := 'lions, tigers, and';
	B := 'bears, oh my!';
	C := '(from the "Wizard of OZ")';

	specialize sort<string>(A, B, C);
	specialize print<string>(A, B, C);

	writeLn;
	I := 77444;
	J :=   -12;
	K :=     0;
	specialize sort<integer>(I, J, K);
	specialize print<integer>(I, J, K);

	writeLn;
	P :=  12.34;
	Q := -56.78;
	R :=   9.01;
	specialize sort<real>(P, Q, R);
	specialize print<real>(P, Q, R)
end.


function bogosort (list)
    if type (list) ~= 'table' then return list end

    -- Fisher-Yates Knuth shuffle
    local function shuffle ()
        local rand = math.random(1,#list)
        for i=1,#list do
            list[i],list[rand] = list[rand],list[i]
            rand = math.random(1,#list)
        end
    end

    -- Returns true only if list is now sorted
    local function in_order ()
        local last = list[1]
        for i,v in next,list do
            if v < last then return false end
            last = v
        end
        return true
    end

    while not in_order() do shuffle() end

    return list
end


divert(-1)
define(`randSeed',141592653)
define(`setRand',
   `define(`randSeed',ifelse(eval($1<10000),1,`eval(20000-$1)',`$1'))')
define(`rand_t',`eval(randSeed^(randSeed>>13))')
define(`random',
   `define(`randSeed',eval((rand_t^(rand_t<<18))&0x7fffffff))randSeed')
define(`for',
   `ifelse($#,0,``$0'',
   `ifelse(eval($2<=$3),1,
   `pushdef(`$1',$2)$4`'popdef(`$1')$0(`$1',incr($2),$3,`$4')')')')
define(`set',`define(`$1[$2]',`$3')')
define(`new',`set($1,size,0)')
define(`get',`defn($1[$2])')
define(`append',
   `set($1,size,incr(get($1,size)))`'set($1,get($1,size),$2)')
define(`deck',
   `new($1)for(`x',1,$2,
         `append(`$1',random)')')
define(`show',
   `for(`x',1,get($1,size),`get($1,x)`'ifelse(x,get($1,size),`',`, ')')')
define(`swap',`set($1,$2,get($1,$4))`'set($1,$4,$3)')
define(`shuffle',
   `for(`x',1,get($1,size),
      `swap($1,x,get($1,x),eval(1+random%get($1,size)))')')
define(`inordern',
   `ifelse(eval($2>=get($1,size)),1,
      1,
      `ifelse(eval(get($1,$2)>get($1,incr($2))),1,
         0,
         `inordern(`$1',incr($2))')')')
define(`inorder',`inordern($1,1)')
define(`bogosort',
   `ifelse(inorder(`$1'),0,`nope shuffle(`$1')`'bogosort(`$1')')')
divert

deck(`b',6)
show(`b')
bogosort(`b')
show(`b')


arr := Array([2,3,1]):
len := numelems(arr):
#Translation of C, random swapping
shuffle_arr := proc(arr, len)
	local i, r, temp:
	for i from 1 to len do
		temp := arr[i]:
		r := rand(1..len)():
		arr[i] := arr[r]:
		arr[r] := temp:
	end do:
end proc:
while(not ListTools:-Sorted(convert(arr, list))) do
	shuffle_arr(arr, len):
end do:
arr;


function list = bogoSort(list)
    while( ~issorted(list) ) %Check to see if it is sorted
        list = list( randperm(numel(list)) ); %Randomly sort the list
    end
end


package main

import (
    "fmt"
    "log"
    "sort"
)

var (
    stringsIn = []string{
        `lions, tigers, and`,
        `bears, oh my!`,
        `(from the "Wizard of OZ")`}
    intsIn = []int{77444, -12, 0}
)

func main() {
    {
        // initialize three vars
        x, y, z := stringsIn[0], stringsIn[1], stringsIn[2]

        // I. Task suggested technique, move values to array (slice).
        // It's consise and relies on library code.
        s := []string{x, y, z}
        sort.Strings(s)
        x, y, z = s[0], s[1], s[2]

        // validate
        if x > y || y > z {
            log.Fatal()
        }

        // II. Likely fastest technique, minimizing tests and data movement.
        // Least consise though, hardest to understand, and most chance to make
        // a coding mistake.
        x, y, z = stringsIn[0], stringsIn[1], stringsIn[2] // (initialize)
        if x < y {
            switch {
            case y < z:
            case x < z:
                y, z = z, y
            default:
                x, y, z = z, x, y
            }
        } else {
            switch {
            case x < z:
                x, y = y, x
            case z < y:
                x, z = z, x
            default:
                x, y, z = y, z, x
            }
        }
        if x > y || y > z { // (validate)
            log.Fatal()
        }

        // III.  A little more consise than II, easier to understand, almost
        // as fast.
        x, y, z = stringsIn[0], stringsIn[1], stringsIn[2] // (initialize)
        if x > y {
            x, y = y, x
        }
        if y > z {
            y, z = z, y
        }
        if x > y {
            x, y = y, x
        }
        if x > y || y > z { // (validate)
            log.Fatal()
        }
        fmt.Println("sorted strings:")
        fmt.Println(" ", x)
        fmt.Println(" ", y)
        fmt.Println(" ", z)
        fmt.Println("original data:")
        fmt.Println(" ", stringsIn[0])
        fmt.Println(" ", stringsIn[1])
        fmt.Println(" ", stringsIn[2])
    }
    // same techniques, with integer test case
    {
        // task suggested technique
        x, y, z := intsIn[0], intsIn[1], intsIn[2] // (initialize)
        s := []int{x, y, z}
        sort.Ints(s)
        x, y, z = s[0], s[1], s[2]
        if x > y || y > z { // (validate)
            log.Fatal()
        }

        // minimizing data movement
        x, y, z = intsIn[0], intsIn[1], intsIn[2] // (initialize)
        if x < y {
            switch {
            case y < z:
            case x < z:
                y, z = z, y
            default:
                x, y, z = z, x, y
            }
        } else {
            switch {
            case x < z:
                x, y = y, x
            case z < y:
                x, z = z, x
            default:
                x, y, z = y, z, x
            }
        }
        if x > y || y > z { // (validate)
            log.Fatal()
        }

        // three swaps
        x, y, z = intsIn[0], intsIn[1], intsIn[2] // (initialize)
        if x > y {
            x, y = y, x
        }
        if y > z {
            y, z = z, y
        }
        if x > y {
            x, y = y, x
        }
        if x > y || y > z { // (validate)
            log.Fatal()
        }
        fmt.Println("sorted ints:", x, y, z)
        fmt.Println("original data:", intsIn)
    }
    // To put any of these techniques in a function, a function could just
    // take three values and return them sorted.
    {
        sort3 := func(x, y, z int) (int, int, int) {
            if x > y {
                x, y = y, x
            }
            if y > z {
                y, z = z, y
            }
            if x > y {
                x, y = y, x
            }
            return x, y, z
        }
        x, y, z := intsIn[0], intsIn[1], intsIn[2] // (initialize)
        x, y, z = sort3(x, y, z)
        if x > y || y > z { // (validate)
            log.Fatal()
        }
    }
    // Alternatively, a function could take pointers
    {
        sort3 := func(x, y, z *int) {
            if *x > *y {
                *x, *y = *y, *x
            }
            if *y > *z {
                *y, *z = *z, *y
            }
            if *x > *y {
                *x, *y = *y, *x
            }
        }
        x, y, z := intsIn[0], intsIn[1], intsIn[2] // (initialize)
        sort3(&x, &y, &z)
        if x > y || y > z { // (validate)
            log.Fatal()
        }
    }
}


fn notSorted arr =
(
    if arr.count > 0 then
    (
        local current = arr[1]
        for i in 2 to arr.count do
        (
            if current > arr[i] then
            (
                return true
            )
            current = arr[i]
        )
    )
    false
)

fn randSort x y =
(
    random -1 1
)

fn shuffle arr =
(
    qsort arr randSort
    arr
)

fn bogosort arr =
(
    while notSorted arr do
    (
        arr = shuffle arr
    )
    arr
)


MODULE Bogo EXPORTS Main;

IMPORT IO, Fmt, Random;

VAR a := ARRAY [1..5] OF INTEGER {1, 2, 3, 4, 5};
    count := 0;

PROCEDURE Shuffle(VAR a: ARRAY OF INTEGER) =
  VAR temp: INTEGER;
  BEGIN
    WITH rand = NEW(Random.Default).init() DO
      FOR i := FIRST(a) TO LAST(a) - 1 DO
        WITH j = rand.integer(i, LAST(a)) DO
          temp := a[i];
          a[i] := a[j];
          a[j] := temp;
        END;
      END;
    END;
  END Shuffle;

PROCEDURE Sorted(VAR a: ARRAY OF INTEGER): BOOLEAN =
  BEGIN
    IF NUMBER(a) <= 1 THEN
      RETURN TRUE;
    END;
    FOR i := FIRST(a) + 1 TO LAST(a) DO
      IF (a[i] < a[i - 1]) THEN
        RETURN FALSE;
      END;
    END;
    RETURN TRUE;
  END Sorted;

BEGIN
  Shuffle(a);
  WHILE NOT Sorted(a) DO
    Shuffle(a);
    INC(count);
  END;
  FOR i := FIRST(a) TO LAST(a) DO
    IO.PutInt(a[i]);
    IO.Put(" ");
  END;
  IO.Put("\nRequired " & Fmt.Int(count) & " shuffles\n");
END Bogo.


import Data.List (sort)

sortedTriple
  :: Ord a
  => (a, a, a) -> (a, a, a)
sortedTriple (x, y, z) =
  let [a, b, c] = sort [x, y, z]
  in (a, b, c)

sortedListfromTriple
  :: Ord a
  => (a, a, a) -> [a]
sortedListfromTriple (x, y, z) = sort [x, y, z]

-- TEST ----------------------------------------------------------------------
main :: IO ()
main = do
  print $
    sortedTriple
      ("lions, tigers, and", "bears, oh my!", "(from the \"Wizard of OZ\")")
  print $
    sortedListfromTriple
      ("lions, tigers, and", "bears, oh my!", "(from the \"Wizard of OZ\")")
  print $ sortedTriple (77444, -12, 0)
  print $ sortedListfromTriple (77444, -12, 0)


100 LET X=77444:LET Y=-12:LET Z=0
110 PRINT X;Y;Z
120 CALL SHORT(X,Y,Z)
130 PRINT X;Y;Z
140 DEF SHORT(REF A,REF B,REF C)
150   IF A>B THEN LET T=A:LET A=B:LET B=T
160   IF B>C THEN LET T=B:LET B=C:LET C=T
170   IF A>B THEN LET T=A:LET A=B:LET B=T
180 END DEF


def sorted(list)
        if len(list) = 0
                return true
        end

        for i in range(0, len(list) - 2)
                if list[i] > list[i + 1]
                        return false
                end
        end

        return true
end

def bogosort(list)
        while not sorted(list)
                list = list.shuffle()
        end

        return list
end


using System;
using System.Console;
using Nemerle.Imperative;

module Bogosort
{
    public static Bogosort[T] (this x : array[T]) : void
      where T : IComparable
    {
        def rnd = Random();
        def shuffle(a)
        {
            foreach (i in [0 .. (a.Length - 2)])
            a[i] <-> a[(rnd.Next(i, a.Length))];
        }

        def isSorted(b)
        {
            when (b.Length <= 1) return true;
            foreach (i in [1 .. (b.Length - 1)])
                when (b[i].CompareTo(b[i - 1]) < 0) return false;
            true;
        }

        def loop()
        {
            unless (isSorted(x)) {shuffle(x); loop();};
        }

        loop()
    }

    Main() : void
    {
        def sortme = array[1, 5, 3, 6, 7, 3, 8, -2];
        sortme.Bogosort();
        foreach (i in sortme) Write($"$i  ");
    }
}


/* NetRexx */
options replace format comments java crossref savelog symbols nobinary

import java.util.List

method isSorted(list = List) private static returns boolean

  if list.isEmpty then
    return isTrue

  it = list.iterator
  last = Comparable it.next
  loop label i_ while it.hasNext
    current = Comparable it.next
    if last.compareTo(current) > 0 then
      return isFalse
    last = current
    end i_

  return isTrue

method bogoSort(list = List) private static
  loop label s_ while \isSorted(list)
    Collections.shuffle(list)
    end s_

  return

method main(args = String[]) public constant
  samples = [int 31, 41, 59, 26, 53, 58, 97, 93, 23, 84]
  alst = ArrayList(samples.length)
  loop iv = 0 to samples.length - 1
    alst.add(Integer(samples[iv]))
    end iv

  say 'unsorted:' alst.toString
  bogoSort(alst)
  say 'sorted:  ' alst.toString

  return

method isTrue public static returns boolean
  return 1 == 1

method isFalse public static returns boolean
  return \isTrue


   x =:  'lions, tigers, and'
   y =:  'bears, oh my!'
   z =:  '(from the "Wizard of OZ")'
   'x y z'=: /:~".'x;y;<z'
   x
(from the "Wizard of OZ")
   y
bears, oh my!
   z
lions, tigers, and

   x =:  77444
   y =:    -12
   z =:      0
   'x y z'=: /:~".'x;y;<z'
   x
_12
   y
0
   z
77444


import java.util.Comparator;
import java.util.stream.Stream;

class Box {
    public int weightKg;

    Box(final int weightKg) {
        this.weightKg = weightKg;
    }
}

public class Sort3Vars {
    public static void main(String... args) {
        int iA = 21;
        int iB = 11;
        int iC = 82;
        int[] sortedInt = Stream.of(iA, iB, iC).sorted().mapToInt(Integer::intValue).toArray();
        iA = sortedInt[0];
        iB = sortedInt[1];
        iC = sortedInt[2];
        System.out.printf("Sorted values: %d %d %d%n", iA, iB, iC);

        String sA = "s21";
        String sB = "s11";
        String sC = "s82";
        Object[] sortedStr = Stream.of(sA, sB, sC).sorted().toArray();
        sA = (String) sortedStr[0];
        sB = (String) sortedStr[1];
        sC = (String) sortedStr[2];
        System.out.printf("Sorted values: %s %s %s%n", sA, sB, sC);

        Box bA = new Box(200);
        Box bB = new Box(12);
        Box bC = new Box(143);
        // Provides a comparator for Box instances
        Object[] sortedBox = Stream.of(bA, bB, bC).sorted(Comparator.comparingInt(a -> a.weightKg)).toArray();
        bA = (Box) sortedBox[0];
        bB = (Box) sortedBox[1];
        bC = (Box) sortedBox[2];
        System.out.printf("Sorted Boxes: %dKg %dKg %dKg%n", bA.weightKg, bB.weightKg, bC.weightKg);
    }
}


import random

randomize()

proc isSorted[T](s: openarray[T]): bool =
  var last = low(T)
  for c in s:
    if c < last:
      return false
    last = c
  return true

proc bogoSort[T](a: var openarray[T]) =
  while not isSorted a: shuffle a

var a = @[4, 65, 2, -31, 0, 99, 2, 83, 782]
bogoSort a
echo a


MODULE Bogo;

   IMPORT Out, Random;

   VAR a: ARRAY 10 OF INTEGER;

   PROCEDURE Init;
      VAR i: INTEGER;
   BEGIN
      FOR i := 0 TO LEN(a) - 1 DO
         a[i] := i + 1;
      END;
   END Init;

   PROCEDURE Sorted(VAR a: ARRAY OF INTEGER): BOOLEAN;
      VAR i: INTEGER;
   BEGIN
      IF LEN(a) <= 1 THEN
         RETURN TRUE;
      END;
      FOR i := 1 TO LEN(a) - 1 DO
         IF (a[i] < a[i - 1]) THEN
            RETURN FALSE;
         END;
      END;
      RETURN TRUE;
   END Sorted;

   PROCEDURE Shuffle*(VAR a: ARRAY OF INTEGER);
      VAR n, t, r: INTEGER;
   BEGIN
      FOR n := 0 TO LEN(a) - 1 DO
         r := Random.Roll(n);
         t := a[n];
         a[n] := a[r];
         a[r] := t;
      END;
   END Shuffle;

BEGIN
   Init;
   Shuffle(a);
   WHILE ~Sorted(a) DO
      Shuffle(a);
   END;
   FOR i := 0 TO LEN(a) - 1 DO
      Out.Int(a[i], 0);
      Out.String(" ");
   END;
   Out.Ln;
END Bogo.


const printThree = (note, [a, b, c], [a1, b1, c1]) => {
  console.log(`${note}
    ${a} is: ${a1}
    ${b} is: ${b1}
    ${c} is: ${c1}
  `);
};
const sortThree = () => {

  let a = 'lions, tigers, and';
  let b = 'bears, oh my!';
  let c = '(from the "Wizard of OZ")';
  printThree('Before Sorting', ['a', 'b', 'c'], [a, b, c]);

  [a, b, c] = [a, b, c].sort();
  printThree('After Sorting', ['a', 'b', 'c'], [a, b, c]);

  let x = 77444;
  let y = -12;
  let z = 0;
  printThree('Before Sorting', ['x', 'y', 'z'], [x, y, z]);

  [x, y, z] = [x, y, z].sort();
  printThree('After Sorting', ['x', 'y', 'z'], [x, y, z]);
};
sortThree();


def example1:
 {x: "lions, tigers, and",
  y: "bears, oh my",
  z: "(from the \"Wizard of OZ\")"
 };

def example2:
 {x: 77444,
  y: -12,
  z: 0
 };


F siftdown(&lst, start, end)
   V root = start
   L
      V child = root * 2 + 1
      I child > end
         L.break
      I child + 1 <= end & lst[child] < lst[child + 1]
         child++
      I lst[root] < lst[child]
         swap(&lst[root], &lst[child])
         root = child
      E
         L.break

F heapsort(&lst)
   L(start) ((lst.len - 2) I/ 2 .. 0).step(-1)
      siftdown(&lst, start, lst.len - 1)

   L(end) (lst.len - 1 .< 0).step(-1)
      swap(&lst[end], &lst[0])
      siftdown(&lst, 0, end - 1)

V arr = [7, 6, 5, 9, 8, 4, 3, 1, 2, 0]
heapsort(&arr)
print(arr)


let rec is_sorted comp = function
 | e1 :: e2 :: r -> comp e1 e2 <= 0 && is_sorted comp (e2 :: r)
 | _             -> true

(* Fisher-Yates shuffle on lists; uses temp array *)
let shuffle l =
  let ar = Array.of_list l in
    for n = Array.length ar - 1 downto 1 do
      let k = Random.int (n+1) in
      let temp = ar.(k) in (* swap ar.(k) and ar.(n) *)
        ar.(k) <- ar.(n);
        ar.(n) <- temp
    done;
    Array.to_list ar

let rec bogosort li =
  if is_sorted compare li then
    li
  else
    bogosort (shuffle li)


declare
  proc {BogoSort Arr}
     for while:{Not {InOrder Arr}} do
        {Shuffle Arr}
     end
  end

  fun {InOrder Arr}
     for I in {Array.low Arr}+1..{Array.high Arr}
	return:Return default:true
     do
        if Arr.(I-1) > Arr.I then {Return false} end
     end
  end

  proc {Shuffle Arr}
     Low = {Array.low Arr}
     High = {Array.high Arr}
  in
     for I in High..Low;~1 do
	J = Low + {OS.rand} mod (I - Low + 1)
        OldI = Arr.I
     in
	Arr.I := Arr.J
        Arr.J := OldI
     end
  end

  X = {Tuple.toArray unit(3 1 4 1 5 9 2 6 5)}
in
  {BogoSort X}
  {Show {Array.toRecord unit X}}


#!/usr/bin/env jsish
/* Sort three variables, in Jsish. semi-colon start/end for unit test echo */

var x =  'lions, tigers, and';
var y =  'bears, oh my!';
var z =  '(from the "Wizard of OZ")';

var arr = [x,y,z];
arr = arr.sort();

;'As strings, before:';
;x;
;y;
;z;

x = arr.shift();
y = arr.shift();
z = arr.shift();

;'x,y,z after:';
;x;
;y;
;z;

x =  77444;
y =    -12;
z =      0;

arr = [x,y,z];
arr = arr.sort();

;'As numbers before:';
;x;
;y;
;z;

x = arr.shift();
y = arr.shift();
z = arr.shift();

;'x,y,z after:';
;x;
;y;
;z;

;'Mixed, integer, float, string';
x =  3.14159;
y =  2;
z =  '1 string';
;x;
;y;
;z;
arr = [x,y,z].sort();
x = arr.shift(); y = arr.shift(); z = arr.shift();
;'x,y,z after:';
;x;
;y;
;z;

/*
=!EXPECTSTART!=
'As strings, before:'
x ==> lions, tigers, and
y ==> bears, oh my!
z ==> (from the "Wizard of OZ")
'x,y,z after:'
x ==> (from the "Wizard of OZ")
y ==> bears, oh my!
z ==> lions, tigers, and
'As numbers before:'
x ==> 77444
y ==> -12
z ==> 0
'x,y,z after:'
x ==> -12
y ==> 0
z ==> 77444
'Mixed, integer, float, string'
x ==> 3.14159
y ==> 2
z ==> 1 string
'x,y,z after:'
x ==> 2
y ==> 3.14159
z ==> 1 string
=!EXPECTEND!=
*/


# v0.6

a, b, c = "lions, tigers, and", "bears, oh my!", "(from the \"Wizard of OZ\")"
a, b, c = sort([a, b, c])
@show a b c

a, b, c = 77444, -12, 0
a, b, c = sort([a, b, c])
@show a b c