#lang racket

(define (sort-disjoint l is)
  (define xs
    (sort (for/list ([x l] [i (in-naturals)] #:when (memq i is)) x) <))
  (let loop ([l l] [i 0] [xs xs])
    (cond [(null? l) l]
          [(memq i is) (cons (car xs) (loop (cdr l) (add1 i) (cdr xs)))]
          [else        (cons (car l)  (loop (cdr l) (add1 i) xs))])))

(sort-disjoint '(7 6 5 4 3 2 1 0) '(6 1 7))
;; --> '(7 0 5 4 3 2 1 6)


my @values  = 7, 6, 5, 4, 3, 2, 1, 0;
my @indices = 6, 1, 7;

@values[ @indices.sort ] .= sort;

say @values;


function list = bubbleSort(list)

    hasChanged = true;
    itemCount = numel(list);

    while(hasChanged)

        hasChanged = false;
        itemCount = itemCount - 1;

        for index = (1:itemCount)

            if(list(index) > list(index+1))
                list([index index+1]) = list([index+1 index]); %swap
                hasChanged = true;
            end %if

        end %for
    end %while
end %bubbleSort


fn bubbleSort arr =
(
    while true do
    (
        changed = false
        for i in 1 to (arr.count - 1) do
        (
            if arr[i] > arr[i+1] then
            (
                swap arr[i] arr[i+1]
                changed = true
            )
        )
        if not changed then exit
    )
    arr
)


/*REXX program uses a   disjointed sublist   to  sort  a  random list  of values.       */
parse arg old ',' idx                            /*obtain the optional lists from the CL*/
if old=''  then old= 7 6 5 4 3 2 1 0             /*Not specified:  Then use the default.*/
if idx=''  then idx= 7 2 8                       /* "      "         "   "   "     "    */
say '  list of indices:'  idx;   say             /*    [↑]  is for one─based lists.     */
say '    unsorted list:'  old                    /*display the  old  list of numbers.   */
say '      sorted list:'  disjoint_sort(old,idx) /*sort 1st list using 2nd list indices.*/
exit                                             /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
disjoint_sort: procedure;    parse arg x,ix;   y=;    z=;    p= 0
               ix= sortL(ix)                           /*ensure the index list is sorted*/
                    do i=1  for  words(ix)             /*extract indexed values from  X.*/
                    z= z   word(x, word(ix, i) )       /*pick the correct value from  X.*/
                    end   /*j*/
               z= sortL(z)                             /*sort extracted (indexed) values*/
                    do m=1  for words(x)               /*re─build (re-populate)  X list.*/
                    if wordpos(m, ix)==0  then y=y  word(x,m)    /*is the same  or  new?*/
                                          else do;  p= p + 1;        y= y word(z, p)
                                               end
                    end   /*m*/
               return strip(y)
/*──────────────────────────────────────────────────────────────────────────────────────*/
sortL: procedure; parse arg L;    n= words(L);       do j=1  for n;        @.j= word(L,j)
                                                     end   /*j*/
         do k=1  for n-1                               /*sort a list using a slow method*/
           do m=k+1  to n;   if @.m<@.k  then parse value   @.k  @.m    with  @.m  @.k
           end   /*m*/
         end     /*k*/                                 /* [↑]  use  PARSE  for swapping.*/
       $= @.1;               do j=2  to n;   $= $ @.j
                             end   /*j*/
       return $


aList = [7, 6, 5, 4, 3, 2, 1, 0]
indList = [7, 2, 8]
bList = []
for n = 1 to len(indList)
    add(bList,[indList[n],aList[indList[n]]])
next
bList1 = sort(bList,1)
bList2 = sort(bList,2)
for n = 1 to len(bList)
    aList[bList1[n][1]] = bList2[n][2]
next
showarray(aList)

func showarray vect
     svect = ""
     for n in vect
         svect += " " + n + ","
     next
     ? "[" + left(svect, len(svect) - 1) + "]"


def sort_disjoint_sublist!(ar, indices)
  values = ar.values_at(*indices).sort
  indices.sort.zip(values).each{ |i,v| ar[i] = v }
  ar
end

values = [7, 6, 5, 4, 3, 2, 1, 0]
indices = [6, 1, 7]
p sort_disjoint_sublist!(values, indices)


Ja        IS $127

          LOC Data_Segment
DataSeg   GREG @
Array     IS @-Data_Segment
          OCTA   999,200,125,1,1020,40,4,5,60,100
ArrayLen  IS (@-Array-Data_Segment)/8

NL        IS  @-Data_Segment
	  BYTE #a,0
	  LOC  @+(8-@)&7

Buffer    IS @-Data_Segment

            LOC #1000
            GREG @
sorted      IS  $5
i           IS  $6
size        IS  $1
a           IS  $0
t           IS  $20
t1          IS  $21
t2          IS  $22
% Input: $0 ptr to array, $1 its length (in octabyte)
% Trashed: $5, $6, $1, $20, $21, $22
BubbleSort  SETL  sorted,1          % sorted = true
            SUB   size,size,1       % size--
            SETL  i,0               % i = 0
3H          CMP   t,i,size          % i < size ?
            BNN   t,1F              % if false, end for loop
            8ADDU $12,i,a           % compute addresses of the
            ADDU  t,i,1             % octas a[i] and a[i+1]
            8ADDU $11,t,a
            LDO   t1,$12,0          % get their values
            LDO   t2,$11,0
            CMP   t,t1,t2           % compare
            BN    t,2F              % if t1<t2, next
            STO   t1,$11,0          % else swap them
            STO   t2,$12,0
            SETL  sorted,0          % sorted = false
2H          INCL  i,1               % i++
            JMP   3B                % next (for loop)
1H          PBZ   sorted,BubbleSort % while sorted is false, loop
            GO    Ja,Ja,0

% Help function (Print an octabyte)
% Input:    $0 (the octabyte)
BufSize     IS    64
            GREG  @
PrintInt8   ADDU  t,DataSeg,Buffer  % get buffer address
            ADDU  t,t,BufSize       % end of buffer
            SETL  t1,0              % final 0 for Fputs
            STB   t1,t,0
1H          SUB   t,t,1             % t--
            DIV   $0,$0,10          % ($0,rR) = divmod($0,10)
            GET   t1,rR             % get reminder
            INCL  t1,'0'            % turn it into ascii digit
            STB   t1,t,0            % store it
            PBNZ  $0,1B             % if $0 /= 0, loop
            OR    $255,t,0          % $255 = t
            TRAP  0,Fputs,StdOut
            GO    Ja,Ja,0           % print and return

Main        ADDU  $0,DataSeg,Array  % $0 = Array address
            SETL  $1,ArrayLen       % $1 = Array Len
            GO    Ja,BubbleSort     % BubbleSort it
            SETL  $4,ArrayLen       % $4 = ArrayLen
	    ADDU  $3,DataSeg,Array  % $3 = Array address
2H          BZ    $4,1F             % if $4 == 0, break
            LDO   $0,$3,0           % $0 = * ($3 + 0)
            GO    Ja,PrintInt8      % print the octa
            ADDU  $255,DataSeg,NL   % add a trailing newline
	    TRAP  0,Fputs,StdOut
            ADDU  $3,$3,8           % next octa
            SUB   $4,$4,1           % $4--
	    JMP   2B                % loop
1H          XOR   $255,$255,$255
            TRAP  0,Halt,0          % exit(0)


sortData$ = "7, 6, 5, 4, 3, 2, 1, 0"
sortIdx$  = "7, 2, 8"

numSort = 8
dim sortData(numSort)
for i = 1 to numSort
   sortData(i) = val(word$(sortData$,i,","))
next i

while word$(sortIdx$,s + 1) <> ""
  s   = s + 1
  idx = val(word$(sortIdx$,s))
  gosub [bubbleSort]
wend
end

[bubbleSort]
sortSw = 1
while sortSw = 1
 sortSw = 0
 for i = idx to numSort - 1              ' start sorting at idx
  if sortData(i) > sortData(i+1) then
     sortSw        = 1
     sortHold      = sortData(i)
     sortData(i)   = sortData(i+1)
     sortData(i+1) = sortHold
  end if
 next i
wend
RETURN


use std::collections::BTreeSet;

fn disjoint_sort(array: &mut [impl Ord], indices: &[usize]) {
    let mut sorted = indices.to_owned();
    sorted.sort_unstable_by_key(|k| &array[*k]);
    indices
        .iter()
        .zip(sorted.iter())
        .map(|(&a, &b)| if a > b { (b, a) } else { (a, b) })
        .collect::<BTreeSet<_>>()
        .iter()
        .for_each(|(a, b)| array.swap(*a, *b))
}

fn main() {
    let mut array = [7, 6, 5, 4, 3, 2, 1, 0];
    let indices = [6, 1, 7];
    disjoint_sort(&mut array, &indices);
    println!("{:?}", array);
}


import scala.compat.Platform

object SortedDisjointSubList extends App {
  val (list, subListIndex) = (List(7, 6, 5, 4, 3, 2, 1, 0), List(6, 1, 7))

  def sortSubList[T: Ordering](indexList: List[Int], list: List[T]) = {
    val subListIndex = indexList.sorted
    val sortedSubListMap = subListIndex.zip(subListIndex.map(list(_)).sorted).toMap

    list.zipWithIndex.map { case (value, index) =>
      if (sortedSubListMap.isDefinedAt(index)) sortedSubListMap(index) else value
    }
  }

  assert(sortSubList(subListIndex, list) == List(7, 0, 5, 4, 3, 2, 1, 6), "Incorrect sort")
  println(s"List in sorted order.\nSuccessfully completed without errors. [total ${Platform.currentTime - executionStart} ms]")
}


(use gauche.sequence)
(define num-list '(7 6 5 4 3 2 1 0))
(define indices '(6 1 7))
(define table
  (alist->hash-table
    (map cons
      (sort indices)
      (sort indices < (lambda (x) (~ num-list x))))))

(map last
  (sort
    (map-with-index
      (lambda (i x) (list (hash-table-get table i i) x))
      num-list)
    <
    car))


PROCEDURE BubbleSort(VAR a: ARRAY OF INTEGER);
  VAR
    changed:        BOOLEAN;
    temp, count, i: INTEGER;
BEGIN
  count := HIGH(a);
  REPEAT
    changed := FALSE;
    DEC(count);
    FOR i := 0 TO count DO
      IF a[i] > a[i+1] THEN
        temp := a[i];
        a[i] := a[i+1];
        a[i+1] := temp;
        changed := TRUE
      END
    END
  UNTIL NOT changed
END BubbleSort;


MODULE Bubble;

PROCEDURE Sort(VAR a: ARRAY OF INTEGER) =
  VAR sorted: BOOLEAN;
      temp, len: INTEGER := LAST(a);
  BEGIN
    WHILE NOT sorted DO
      sorted := TRUE;
      DEC(len);
      FOR i := FIRST(a) TO len DO
        IF a[i+1] < a[i] THEN
          temp := a[i];
          a[i] := a[i + 1];
          a[i + 1] := temp;
          sorted := FALSE;
        END;
      END;
    END;
  END Sort;
END Bubble.


func disjointSort(values, indices) {
    values[indices.sort] = [values[indices]].sort...
}

var values =  [7, 6, 5, 4, 3, 2, 1, 0];
var indices = [6, 1, 7];

disjointSort(values, indices);
say values;


functor SortDisjointFn (A : MONO_ARRAY) : sig
    val sort : (A.elem * A.elem -> order) -> (A.array * int array) -> unit
  end = struct

    structure DisjointView : MONO_ARRAY = struct
      type elem = A.elem
      type array = A.array * int array
      fun length (a, s) = Array.length s
      fun sub ((a, s), i) = A.sub (a, Array.sub (s, i))
      fun update ((a, s), i, x) = A.update (a, Array.sub (s, i), x)

      (* dummy implementations for not-needed functions *)
      type vector = unit
      val maxLen = Array.maxLen
      fun array _ = raise Domain
      fun fromList _ = raise Domain
      fun tabulate _ = raise Domain
      fun vector _ = raise Domain
      fun copy _ = raise Domain
      fun copyVec _ = raise Domain
      fun appi _ = raise Domain
      fun app _ = raise Domain
      fun modifyi _ = raise Domain
      fun modify _ = raise Domain
      fun foldli _ = raise Domain
      fun foldl _ = raise Domain
      fun foldri _ = raise Domain
      fun foldr _ = raise Domain
      fun findi _ = raise Domain
      fun find _ = raise Domain
      fun exists _ = raise Domain
      fun all _ = raise Domain
      fun collate _ = raise Domain
    end

    structure DisjointViewSort = ArrayQSortFn (DisjointView)

    fun sort cmp (arr, indices) = (
      ArrayQSort.sort Int.compare indices;
      DisjointViewSort.sort cmp (arr, indices)
    )
  end


struct DisjointSublistView<T> : MutableCollectionType {
  let array : UnsafeMutablePointer<T>
  let indexes : [Int]

  subscript (position: Int) -> T {
    get {
      return array[indexes[position]]
    }
    set {
      array[indexes[position]] = newValue
    }
  }
  var startIndex : Int { return 0 }
  var endIndex : Int { return indexes.count }
  func generate() -> IndexingGenerator<DisjointSublistView<T>> { return IndexingGenerator(self) }
}

func sortDisjointSublist<T : Comparable>(inout array: [T], indexes: [Int]) {
  var d = DisjointSublistView(array: &array, indexes: sorted(indexes))
  sort(&d)
}

var a = [7, 6, 5, 4, 3, 2, 1, 0]
let ind = [6, 1, 7]
sortDisjointSublist(&a, ind)
println(a)


package require Tcl 8.5
proc disjointSort {values indices args} {
    # Ensure that we have a unique list of integers, in order
    # We assume there are no end-relative indices
    set indices [lsort -integer -unique $indices]
    # Map from those indices to the values to sort
    set selected {}
    foreach i $indices {lappend selected [lindex $values $i]}
    # Sort the values (using any extra options) and write back to the list
    foreach i $indices v [lsort {*}$args $selected] {
	lset values $i $v
    }
    # The updated list is the result
    return $values
}


.ig
Bubble sort algorithm in Troff
==============================

:For: Rosetta Code
:Author: Stephanie Björk (Katt)
:Date: December 1, 2017
..
.ig
Array implementation: \(*A
---------------------------
This is an array implementation that takes advantage of Troff's numerical
registers.  Registers ``Ax``, where ``x`` is a base-10 Hindu-Arabic numeral and
0 < ``x`` < \(if, are used by array \(*A.  The array counter which holds the
number of items in the array is stored in register ``Ac``.  This array
implementation is one-indexed (array elements count from 1), though it could be
hardcoded again to become zero-indexed depending on what the programmer favours.
..
.nr Ac 0 1 \" Array counter
.
.de APUSH
.nr A\\n+(Ac \\$1
.. \" de APUSH
.
.de AREADLN
.APUSH \\$1
.if \\n(.$>1 \{ \
.	shift
.	AREADLN \\$*
\} \" if \\n(.$>1
.. \" de AREADLN
.
.de ASWAP
.nr tmp \\n[A\\$1]
.nr A\\$1 \\n[A\\$2]
.nr A\\$2 \\n[tmp]
.rm tmp
.. \" de ASWAP
.
.de ASORT
.nr swapped 1
.nr Ad \\n(Ac+1
.while \\n[swapped] \{ \
.	nr swapped 0
.	nr Ai 1
.	nr Ad -1
.	while \\n(Ai<\\n(Ad \{ \
.		nr Aj \\n(Ai+1
.		if \\n[A\\n(Ai]>\\n[A\\n(Aj] \{ \
.			ASWAP \\n(Ai \\n(Aj
.			nr swapped 1
\} \" if \\n[A\\n(Ai]>\\n[A\\n(Aj]
.		nr Ai +1
\} \" while \\n(Ai<\\n(Ac
\} \" while \\n[swapped]
.. \" de ASORT
.
.ig
Begin Program
-------------
The program's procedural body.  Here, we push all our potentially-unsorted
integer tokens sequentially, call a subroutine to sort them, and print all the
sorted items.
..
.AREADLN 12 87 23 77 0 66 45 92 3 0 2 1 9 9 5 4 4 4 \" Our input items to sort.
.ASORT \" Sort all items in the array.
.
.\" Output sorted items
.nr Ai 0 1
.while \n(Ai<\n(Ac \n[A\n+[Ai]]


def bubble_sort(seq)
	changed = true

	while changed
		changed = false
		for i in range(0, len(seq) - 2)
			if seq[i] > seq[i + 1]
				temp = seq[i]
				seq[i] = seq[i + 1]
				seq[i + 1] = temp
				changed = true
			end
		end
	end

	return seq
end

if main
	import Nanoquery.Util; random = new(Random)

	testset = list(range(0, 99))
	testset = random.shuffle(testset)
	println testset + "\n"

	testset = bubble_sort(testset)
	println testset
end


$$ MODE TUSCRIPT
values="7'6'5'4'3'2'1'0"
indices="7'2'8"
v_unsorted=SELECT (values,#indices)
v_sort=DIGIT_SORT (v_unsorted)
i_sort=DIGIT_SORT (indices)
LOOP i=i_sort,v=v_sort
values=REPLACE (values,#i,v)
ENDLOOP
PRINT values


import "/sort" for Sort

// sorts values in place, leaves indices unsorted
var sortDisjoint = Fn.new { |values, indices|
    var sublist = []
    for (ix in indices) sublist.add(values[ix])
    Sort.quick(sublist)
    var i = 0
    var indices2 = Sort.merge(indices)
    for (ix in indices2) {
        values[ix] = sublist[i]
        i = i + 1
    }
}

var values  = [7, 6, 5, 4, 3, 2, 1, 0]
var indices = [6, 1, 7]
System.print("Initial: %(values)")
sortDisjoint.call(values, indices)
System.print("Sorted : %(values)")


using System;
using System.Console;

module Bubblesort
{
    Bubblesort[T] (x : list[T]) : list[T]
      where T : IComparable
    {
        def isSorted(y)
        {
            |[_] => true
            |y1::y2::ys => (y1.CompareTo(y2) < 0) && isSorted(y2::ys)
        }

        def sort(y)
        {
            |[y]        => [y]
            |y1::y2::ys => if (y1.CompareTo(y2) < 0) y1::sort(y2::ys)
                           else y2::sort(y1::ys)
        }

        def loop(y)
        {
            if (isSorted(y)) y else {def z = sort(y); loop(z)}
        }

        match(x)
        {
            |[]  => []
            |_   => loop(x)
        }
    }

    Main() : void
    {
        def empty = [];
        def single = [2];
        def several = [2, 6, 1, 7, 3, 9, 4];
        WriteLine(Bubblesort(empty));
        WriteLine(Bubblesort(single));
        WriteLine(Bubblesort(several));
    }
}


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

placesList = [String -
    "UK  London",     "US  New York"   -
  , "US  Boston",     "US  Washington" -
  , "UK  Washington", "US  Birmingham" -
  , "UK  Birmingham", "UK  Boston"     -
]
sortedList = bubbleSort(String[] Arrays.copyOf(placesList, placesList.length))

lists = [placesList, sortedList]
loop ln = 0 to lists.length - 1
  cl = lists[ln]
  loop ct = 0 to cl.length - 1
    say cl[ct]
    end ct
    say
  end ln

return

method bubbleSort(list = String[]) public constant binary returns String[]

listLen = list.length
loop i_ = 0 to listLen - 1
  loop j_ = i_ + 1 to listLen - 1
    if list[i_].compareTo(list[j_]) > 0 then do
      tmpstor  = list[j_]
      list[j_] = list[i_]
      list[i_] = tmpstor
      end
    end j_
  end i_

return list


include xpllib;         \for Sort routine
int  Values, Indices, J, I, T;
[Values:= [7, 6, 5, 4, 3, 2, 1, 0];
Indices:= [6, 1, 7];
Sort(Indices, 3);
for J:= 3-1 downto 0 do \bubble sort values at Indices
    for I:= 0 to J-1 do
        if Values(Indices(I)) > Values(Indices(I+1)) then
            [T:= Values(Indices(I));
            Values(Indices(I)):= Values(Indices(I+1));
            Values(Indices(I+1)):= T;
            ];
for I:= 0 to 8-1 do
        [IntOut(0, Values(I));  ChOut(0, ^ )];
]


values :=T(7, 6, 5, 4, 3, 2, 1, 0);
indices:=T(6, 1, 7);

indices.apply(values.get).sort() // a.get(0) == a[0]
  .zip(indices.sort()) //-->(v,i) == L(L(0,1),L(1,6),L(6,7))
  .reduce(fcn(newList,[(v,i)]){ newList[i]=v; newList },values.copy())
  .println();  // new list


proc bubbleSort[T](a: var openarray[T]) =
  var t = true
  for n in countdown(a.len-2, 0):
    if not t: break
    t = false
    for j in 0..n:
      if a[j] <= a[j+1]: continue
      swap a[j], a[j+1]
      t = true

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


function : Swap(p : Int[]) ~ Nil {
  t := p[0];
  p[0] := p[1];
  p[1] := t;
}

function : Sort(a : Int[]) ~ Nil {
  do {
    sorted := true;
    size -= 1;
    for (i:=0; i<a->Size(); i+=1;) {
      if (a[i+1] < a[i]) {
        swap(a+i);
        sorted := 0;
      };
    };
  }
  while (sorted = false);
}


- (NSArray *) bubbleSort:(NSMutableArray *)unsorted {
    BOOL done = false;

    while (!done) {
        done = true;
        for (int i = 1; i < unsorted.count; i++) {
            if ( [[unsorted objectAtIndex:i-1] integerValue] > [[unsorted objectAtIndex:i] integerValue] ) {
                [unsorted exchangeObjectAtIndex:i withObjectAtIndex:i-1];
                done = false;
            }
        }
    }

    return unsorted;
}


let rec bsort s =
  let rec _bsort = function
    | x :: x2 :: xs when x > x2 ->
        x2 :: _bsort (x :: xs)
    | x :: x2 :: xs ->
        x :: _bsort (x2 :: xs)
    | s -> s
  in
  let t = _bsort s in
    if t = s then t
    else bsort t


function s = bubblesort(v)
  itemCount = length(v);
  do
    hasChanged = false;
    itemCount--;
    for i = 1:itemCount
      if ( v(i) > v(i+1) )
	v([i,i+1]) = v([i+1,i]);  % swap
	hasChanged = true;
      endif
    endfor
  until(hasChanged == false)
  s = v;
endfunction


(define (bubble-sort x ??)
   (define (sort-step l)
      (if (or (null? l) (null? (cdr l)))
         l
         (if (?? (car l) (cadr l))
            (cons (cadr l) (sort-step (cons (car l) (cddr l))))
            (cons (car  l) (sort-step (cdr l))))))
   (let loop ((i x))
      (if (equal? i (sort-step i))
         i
         (loop (sort-step i)))))

(print
   (bubble-sort (list 1 3 5 9 8 6 4 3 2) >))
(print
   (bubble-sort (iota 100) >))
(print
   (bubble-sort (iota 100) <))


/* Rexx */
Do
  placesList = sampleData()
  call show placesList
  say
  sortedList = bubbleSort(placesList)
  call show sortedList
  say

  return
End
Exit

-- -----------------------------------------------------------------------------
bubbleSort:
procedure
Do
  il = arg(1)
  sl = il~copy

  listLen = sl~size
  loop i_ = 1 to listLen
    loop j_ = i_ + 1 to listLen
      cmpi = sl[i_]
      cmpj = sl[j_]
      if cmpi > cmpj then do
        sl[i_] = cmpj
        sl[j_] = cmpi
        end
      end j_
    end i_
  return sl
End
Exit

-- -----------------------------------------------------------------------------
show:
procedure
Do
  al = arg(1)

  loop e_ over al
    say e_
    end e_

  return
End
Exit

-- -----------------------------------------------------------------------------
sampleData:
procedure
Do
  placesList = .array~of( ,
    "UK  London",     "US  New York",   "US  Boston",     "US  Washington", ,
    "UK  Washington", "US  Birmingham", "UK  Birmingham", "UK  Boston"      ,
    )

  return placesList
End
Exit


declare
  proc {BubbleSort Arr}
     proc {Swap I J}
        Arr.J := (Arr.I := Arr.J) %% assignment returns the old value
     end
     IsSorted = {NewCell false}
     MaxItem = {NewCell {Array.high Arr}-1}
  in
     for until:@IsSorted do
        IsSorted := true
        for I in {Array.low Arr}[email protected]MaxItem do
           if Arr.I > Arr.(I+1) then
              IsSorted := false
              {Swap I I+1}
           end
        end
        MaxItem := @MaxItem - 1
     end
  end
  Arr = {Tuple.toArray unit(10 9 8 7 6 5 4 3 2 1)}
in
  {BubbleSort Arr}
  {Inspect Arr}


procedure bubble_sort(var list: array of real);
var
  i, j, n: integer;
  t: real;
begin
  n := length(list);
  for i := n downto 2 do
    for j := 0 to i - 1 do
      if list[j] > list[j + 1] then
      begin
        t := list[j];
        list[j] := list[j + 1];
        list[j + 1] := t;
      end;
end;


with javascript_semantics

function bubble_sort(sequence s)
    s = deep_copy(s)
    for j=length(s) to 1 by -1 do
        integer changed = 0
        for i=1 to j-1 do
            object si = s[i],
                   sn = s[i+1]
            if si>sn then
                s[i] = sn
                s[i+1] = si
                changed = 1
            end if
        end for
        if changed=0 then exit end if
    end for
    return s
end function

constant s = {4, 15, "delta", 2, -31, 0, "alfa", 19, "gamma", 2, 13, "beta", 782, 1}

puts(1,"Before: ")
?s
puts(1,"After: ")
?bubble_sort(s)


function bubbleSort(array $array){
    foreach($array as $i => &$val){
        foreach($array as $k => &$val2){
            if($k <= $i)
                continue;
            if($val > $val2) {
                list($val, $val2) = [$val2, $val];
                break;
            }
        }
    }
    return $array;
}


(de bubbleSort (Lst)
   (use Chg
      (loop
         (off Chg)
         (for (L Lst (cdr L) (cdr L))
            (when (> (car L) (cadr L))
               (xchg L (cdr L))
               (on Chg) ) )
         (NIL Chg Lst) ) ) )


/* A primitive bubble sort */
bubble_sort: procedure (A);
   declare A(*) fixed binary;
   declare temp fixed binary;
   declare i fixed binary, no_more_swaps bit (1) aligned;

   do until (no_more_swaps);
      no_more_swaps = true;
      do i = lbound(A,1) to hbound(A,1)-1;
         if A(i) > A(i+1) then
            do; temp = A(i); A(i) = A(i+1); A(i+1) = temp;
                no_more_swaps = false;
            end;
      end;
   end;
end bubble_sort;


define bubble_sort(v);
lvars n=length(v), done=false, i;
while not(done) do
   true -> done;
   n - 1 -> n;
   for i from 1 to n do
      if v(i) > v(i+1) then
         false -> done;
         ;;; Swap using multiple assignment
         (v(i+1), v(i)) -> (v(i), v(i+1));
      endif;
   endfor;
endwhile;
enddefine;

;;; Test it
vars ar = { 10 8 6 4 2 1 3 5 7 9};
bubble_sort(ar);
ar =>


/bubblesort{
/x exch def
/temp x x length 1 sub get def
/i x length 1 sub def
/j i 1 sub def

x length 1 sub{
i 1 sub{
x j 1 sub get x j get lt
{
/temp x j 1 sub get def
x j 1 sub x j get put
x j temp put
}if
/j j 1 sub def
}repeat
/i i 1 sub def
/j i 1 sub def
}repeat
x pstack
}def


function bubblesort ($a) {
    $l = $a.Length
    $hasChanged = $true
    while ($hasChanged) {
        $hasChanged = $false
        $l--
        for ($i = 0; $i -lt $l; $i++) {
            if ($a[$i] -gt $a[$i+1]) {
                $a[$i], $a[$i+1] = $a[$i+1], $a[$i]
                $hasChanged = $true
            }
        }
    }
}


%___________________________________________________________________________
% Bubble sort

bubble(0, Res, Res, sorted).
bubble(Len, [A,B|T], Res, unsorted) :- A > B, !, bubble(Len,[B,A|T], Res, _).
bubble(Len, [A|T], [A|Ts], Ch) :- L is Len-1, bubble(L, T, Ts, Ch).

bubblesort(In, Out) :- length(In, Len), bubblesort(Len, In, Out).
bubblesort(0, In, In).
bubblesort(Len, In, Out) :-
	bubble(Len, In, Bubbled, SortFlag),  % bubble the list
	(SortFlag=sorted -> Out=Bubbled;     % list is already sorted
	 SegLen is Len - 1,		     % one fewer to process
	 writef('bubbled=%w\n', [Bubbled]),  % show progress
	 bubblesort(SegLen, Bubbled, Out)).

test :-  In = [8,9,1,3,4,2,6,5,4],
	 writef('  input=%w\n', [In]),
	 bubblesort(In, R),
	 writef('-> %w\n', [R]).


Procedure bubbleSort(Array a(1))
  Protected i, itemCount, hasChanged

  itemCount = ArraySize(a())
  Repeat
    hasChanged = #False
    itemCount - 1
    For i = 0 To itemCount
      If a(i) > a(i + 1)
        Swap a(i), a(i + 1)
        hasChanged = #True
      EndIf
    Next
  Until hasChanged = #False
EndProcedure


def bubble_sort(seq):
    """Inefficiently sort the mutable sequence (list) in place.
       seq MUST BE A MUTABLE SEQUENCE.

       As with list.sort() and random.shuffle this does NOT return
    """
    changed = True
    while changed:
        changed = False
        for i in range(len(seq) - 1):
            if seq[i] > seq[i+1]:
                seq[i], seq[i+1] = seq[i+1], seq[i]
                changed = True
    return seq

if __name__ == "__main__":
   """Sample usage and simple test suite"""

   from random import shuffle

   testset = [_ for _ in range(100)]
   testcase = testset.copy() # make a copy
   shuffle(testcase)
   assert testcase != testset  # we've shuffled it
   bubble_sort(testcase)
   assert testcase == testset  # we've unshuffled it back into a copy


  [ stack ]                  is sorted (       --> s )

  [ rot tuck over peek
    2swap tuck over peek
    dip rot 2dup < iff
      [ dip [ unrot poke ]
        swap rot poke
        sorted release
        false sorted put ]
    else
      [ drop 2drop nip ] ]   is >exch  ( [ n n --> [ )

  [ dup size 1 - times
     [ true sorted put
       i 1+ times
         [ i^ dup 1+ >exch ]
       sorted take if
         conclude ] ]        is bubble (     [ --> [ )

  [] 20 times
    [ 10 random join ]
  say "Before: " dup echo cr
  say "After:  " bubble echo


(define bubble-shot
  [A]     -> [A]
  [A B|R] -> [B|(bubble-shot [A|R])] where (> A B)
  [A  |R] -> [A|(bubble-shot R)])

(define bubble-sort
  X -> (fix bubble-shot X))

(bubble-sort [6 8 5 9 3 2 2 1 4 7])


bubbleSort <- function(items)
{
  repeat
  {
    if((itemCount <- length(items)) <= 1) return(items)
    hasChanged <- FALSE
    itemCount <- itemCount - 1
    for(i in seq_len(itemCount))
    {
      if(items[i] > items[i + 1])
      {
        items[c(i, i + 1)] <- items[c(i + 1, i)]#The cool trick mentioned above.
        hasChanged <- TRUE
      }
    }
    if(!hasChanged) break
  }
  items
}
#Examples taken from the Haxe solution.
ints <- c(1, 10, 2, 5, -1, 5, -19, 4, 23, 0)
numerics <- c(1, -3.2, 5.2, 10.8, -5.7, 7.3, 3.5, 0, -4.1, -9.5)
strings <- c("We", "hold", "these", "truths", "to", "be", "self-evident", "that", "all", "men", "are", "created", "equal")


class BubbleSort
	**Sort a list with the Bubble Sort algorithm**

	on start

		args := program arguments
		.sort(args)
		print args

	define sort(list) is shared
		**Sort the list**

		test
			list := [4, 2, 7, 3]
			.sort(list)
			assert list = [2, 3, 4, 7]

		body
			last := list.count - 1

			post while changed

				changed := false

				for i in last

					if list[i] > list[i + 1]
						temp := list[i]
						list[i] := list[i + 1]
						list[i + 1] := temp
						changed := true


#lang racket

(define (bubble-sort <? v)
  (define len (vector-length v))
  (define ref vector-ref)
  (let loop ([max len]
             [again? #f])
    (for ([i (in-range 0 (- max 1))]
          [j (in-range 1 max)])
      (define vi (ref v i))
      (when (<? (ref v j) vi)
        (vector-set! v i (ref v j))
        (vector-set! v j vi)
        (set! again? #t)))
    (when again? (loop (- max 1) #f)))
  v)


  Dim sortable() As Integer = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
  sortable.Shuffle() ' sortable is now randomized
  Dim swapped As Boolean
  Do
    Dim index, bound As Integer
    bound = sortable.Ubound

    While index < bound
      If sortable(index) > sortable(index + 1) Then
        Dim s As Integer = sortable(index)
        sortable.Remove(index)
        sortable.Insert(index + 1, s)
        swapped = True
      End If
      index = index + 1
    Wend

  Loop Until Not swapped
'sortable is now sorted


/*REXX program sorts an array  (of any kind of items)  using the  bubble─sort algorithm.*/
call gen                                         /*generate the array elements  (items).*/
call show   'before sort'                        /*show the  before  array elements.    */
     say copies('▒', 70)                         /*show a separator line (before/after).*/
call bSort         #                             /*invoke the bubble sort  with # items.*/
call show   ' after sort'                        /*show the  after   array elements.    */
exit                                             /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
bSort: procedure expose @.;  parse arg n         /*N: is the number of @ array elements.*/
         do m=n-1  by -1  until ok;         ok=1 /*keep sorting the  @ array until done.*/
           do j=1  for m;  k=j+1;  if @.j<[email protected].k  then iterate       /*elements in order? */
           [email protected].j;  @.[email protected].k;  @.k=_;         ok=0 /*swap two elements;  flag as not done.*/
           end   /*j*/
         end     /*m*/;        return
/*──────────────────────────────────────────────────────────────────────────────────────*/
gen: @.=;         @.1 = '---letters of the Hebrew alphabet---' ;   @.13= "kaph    [kaf]"
                  @.2 = '====================================' ;   @.14= "lamed"
                  @.3 = 'aleph   [alef]'                       ;   @.15= "mem"
                  @.4 = 'beth    [bet]'                        ;   @.16= "nun"
                  @.5 = 'gimel'                                ;   @.17= "samekh"
                  @.6 = 'daleth  [dalet]'                      ;   @.18= "ayin"
                  @.7 = 'he'                                   ;   @.19= "pe"
                  @.8 = 'waw     [vav]'                        ;   @.20= "sadhe   [tsadi]"
                  @.9 = 'zayin'                                ;   @.21= "qoph    [qof]"
                  @.10= 'heth    [het]'                        ;   @.22= "resh"
                  @.11= 'teth    [tet]'                        ;   @.23= "shin"
                  @.12= 'yod'                                  ;   @.24= "taw     [tav]"
        do #=1  until @.#=='';  end;      #=#-1  /*determine #elements in list; adjust #*/
     return
/*──────────────────────────────────────────────────────────────────────────────────────*/
show:   do j=1  for #; say '     element' right(j,length(#)) arg(1)":"  @.j; end;   return


bubbleList = [4,2,1,3]
flag = 0
bubbleSort(bubbleList)
see bubbleList

func bubbleSort A
     n = len(A)
     while flag = 0
           flag = 1
           for i = 1 to n-1
               if A[i] > A[i+1]
                  temp = A[i]
                  A[i] = A[i+1]
                  A[i+1] = temp
                  flag = 0
                ok
            next
      end


class Array
  def bubblesort1!
    length.times do |j|
      for i in 1...(length - j)
        if self[i] < self[i - 1]
          self[i], self[i - 1] = self[i - 1], self[i]
        end
      end
    end
    self
  end
   def bubblesort2!
    each_index do |index|
      (length - 1).downto( index ) do |i|
        self[i-1], self[i] = self[i], self[i-1] if self[i-1] < self[i]
      end
    end
    self
  end
end
ary = [3, 78, 4, 23, 6, 8, 6]
ary.bubblesort1!
p ary
# => [3, 4, 6, 6, 8, 23, 78]


siz = 100
dim data$(siz)
unSorted = 1

WHILE unSorted
  unSorted = 0
  FOR i = 1 TO siz -1
    IF data$(i) > data$(i + 1) THEN
      tmp       = data$(i)
      data$(i)  = data$(i + 1)
      data$(i + 1) = tmp
      unSorted  = 1
    END IF
  NEXT
WEND


fn bubble_sort<T: Ord>(values: &mut[T]) {
    let mut n = values.len();
    let mut swapped = true;

    while swapped {
        swapped = false;

        for i in 1..n {
            if values[i - 1] > values[i] {
                values.swap(i - 1, i);
                swapped = true;
            }
        }

        n = n - 1;
    }
}

fn main() {
    // Sort numbers.
    let mut numbers = [8, 7, 1, 2, 9, 3, 4, 5, 0, 6];
    println!("Before: {:?}", numbers);

    bubble_sort(&mut numbers);
    println!("After: {:?}", numbers);

    // Sort strings.
    let mut strings = ["empty", "beach", "art", "car", "deal"];
    println!("Before: {:?}", strings);

    bubble_sort(&mut strings);
    println!("After: {:?}", strings);
}


class SORT{T < $IS_LT{T}} is
  private swap(inout a, inout b:T) is
    temp ::= a;
    a := b;
    b := temp;
  end;
  bubble_sort(inout a:ARRAY{T}) is
    i:INT;
    if a.size < 2 then return; end;
    loop
      sorted ::= true;
      loop i := 0.upto!(a.size - 2);
        if a[i+1] < a[i] then
          swap(inout a[i+1], inout a[i]);
          sorted := false;
        end;
      end;
      until!(sorted);
    end;
  end;
end;


def bubbleSort[T](arr: Array[T])(implicit o: Ordering[T]) {
  import o._
  val consecutiveIndices = (arr.indices, arr.indices drop 1).zipped
  var hasChanged = true
  do {
    hasChanged = false
    consecutiveIndices foreach { (i1, i2) =>
      if (arr(i1) > arr(i2)) {
        hasChanged = true
        val tmp = arr(i1)
        arr(i1) = arr(i2)
        arr(i2) = tmp
      }
    }
  } while(hasChanged)
}


(define (bubble-sort x gt?)
  (letrec
    ((fix (lambda (f i)
       (if (equal? i (f i))
           i
           (fix f (f i)))))

     (sort-step (lambda (l)
        (if (or (null? l) (null? (cdr l)))
            l
            (if (gt? (car l) (cadr l))
                (cons (cadr l) (sort-step (cons (car l) (cddr l))))
                (cons (car  l) (sort-step (cdr l))))))))

  (fix sort-step x)))


function b=BubbleSort(a)
  n=length(a)
  swapped=%T
  while swapped
    swapped=%F
    for i=1:1:n-1
      if a(i)>a(i+1) then
        temp=a(i)
        a(i)=a(i+1)
        a(i+1)=temp
        swapped=%T
      end
    end
  end
  b=a
endfunction BubbleSort


const proc: bubbleSort (inout array elemType: arr) is func
  local
    var boolean: swapped is FALSE;
    var integer: i is 0;
    var elemType: help is elemType.value;
  begin
    repeat
      swapped := FALSE;
      for i range 1 to length(arr) - 1 do
        if arr[i] > arr[i + 1] then
          help := arr[i];
          arr[i] := arr[i + 1];
          arr[i + 1] := help;
          swapped := TRUE;
        end if;
      end for;
    until not swapped;
  end func;


(tc +)

(define swap
  { (vector number) --> number --> number --> (vector number) }
  A I1 I2 -> (let Z (<-vector A I1)
               (do (vector-> A I1 (<-vector A I2))
                   (vector-> A I2 Z))))

(define one-pass
  { (vector number) --> number --> boolean --> number --> boolean }
  A N Swapped N -> (do (if (> (<-vector A (- N 1)) (<-vector A N))
                           (swap A (- N 1) N))
                       Swapped)
  A N Swapped I -> (if (> (<-vector A (- I 1)) (<-vector A I))
                       (do (swap A (- I 1) I)
                           (one-pass A N true (+ I 1)))
                       (one-pass A N Swapped (+ I 1))))

(define bubble-h
  { boolean --> (vector number) --> number --> (vector number) }
  true A N -> (bubble-h (one-pass A N false 2) A N)
  false A N -> A)

(define bubble-sort
  { (vector number) --> (vector number) }
  A -> (let N (limit A)
         (bubble-h (one-pass A N false 2) A N)))


func bubble_sort(arr) {
    loop {
        var swapped = false
        { |i|
            if (arr[i] > arr[i+1]) {
                arr[i, i+1] = arr[i+1, i]
                swapped = true
            }
        } << ^arr.end
        swapped || break
    }
    return arr
}


BEGIN

    PROCEDURE BUBBLESORT(A); NAME A; INTEGER ARRAY A;
    BEGIN
       INTEGER LOW, HIGH, I;
       BOOLEAN SWAPPED;

       PROCEDURE SWAP(I, J); INTEGER I, J;
       BEGIN
           INTEGER TEMP;
           TEMP := A(I); A(I) := A(J); A(J) := TEMP;
       END**OF**SWAP;

       LOW := LOWERBOUND(A, 1);
       HIGH := UPPERBOUND(A, 1);
       SWAPPED := TRUE;
       WHILE SWAPPED DO
       BEGIN
         SWAPPED := FALSE;
         FOR I := LOW + 1 STEP 1 UNTIL HIGH DO
         BEGIN
           COMMENT IF THIS PAIR IS OUT OF ORDER ;
           IF A(I - 1) > A(I) THEN
           BEGIN
             COMMENT SWAP THEM AND REMEMBER SOMETHING CHANGED ;
             SWAP(I - 1, I);
             SWAPPED := TRUE;
           END;
         END;
       END;
    END**OF**BUBBLESORT;

    INTEGER ARRAY A(1:10);
    INTEGER I, N;
    I := 1;
    FOR N := 6, 8, 5, 9, 3, 2, 2, 1, 4, 7 DO
    BEGIN
        A(I) := N; I := I + 1;
    END;
    BUBBLESORT(A);
    FOR I:= 1 STEP 1 UNTIL 10 DO
        OUTINT(A(I), 5);
    OUTIMAGE;

END;


|item swap itemCount hasChanged|
item := #(1 4 5 6 10 8 7 61 0 -3) copy.
swap :=
	[:indexOne :indexTwo|
	|temp|
	temp := item at: indexOne.
	item at: indexOne put: (item at: indexTwo).
	item at: indexTwo put: temp].

itemCount := item size.
[hasChanged := false.
itemCount := itemCount - 1.
1 to: itemCount do:
	[:index |
	(item at: index) > (item at: index + 1) ifTrue:
		[swap value: index value: index + 1.
		hasChanged := true]].
hasChanged] whileTrue.


*       # Sort array in place, return array
        define('bubble(a,alen)i,j,ub,tmp') :(bubble_end)
bubble  i = 1; ub = alen
outer   gt(ub,1) :f(bdone)
        j = 1
inner   le(a<j>, a<j + 1>) :s(incrj)
        tmp = a<j>
        a<j> = a<j + 1>
        a<j + 1> = tmp
incrj   j = lt(j + 1,ub) j + 1 :s(inner)
        ub = ub - 1 :(outer)
bdone   bubble = a :(return)
bubble_end

*       # Fill array with test data
        str = '33 99 15 54 1 20 88 47 68 72'
        output = str; arr = array(10)
floop   i = i + 1; str span('0123456789') . arr<i> = :s(floop)

*       # Test and display
        bubble(arr,10); str = ''
sloop   j = j + 1; str = str arr<j> ' ' :s(sloop)
        output = trim(str)
end


package Bubble
is

   type Arr is array(Integer range <>) of Integer;

   procedure Sort (A : in out Arr);
   --# derives A from *;

end Bubble;

package body Bubble
is
   procedure Sort (A : in out Arr)
   is
      Finished : Boolean;
      Temp     : Integer;
   begin
      if A'Last /= A'First then
         loop
            Finished := True;
            for J in Integer range A'First .. A'Last - 1 loop
               if A (J + 1) < A (J) then
                  Finished := False;
                  Temp := A (J + 1);
                  A (J + 1) := A (J);
                  A (J) := Temp;
               end if;
            end loop;
            --# assert A'Last /= A'First;
            exit when Finished;
         end loop;
      end if;
   end Sort;

end Bubble;


fun bubble_select [] = []
  | bubble_select [a] = [a]
  | bubble_select (a::b::xs) =
    if b < a then b::(bubble_select(a::xs)) else a::(bubble_select(b::xs))

fun bubblesort [] = []
  | bubblesort (x::xs) =bubble_select (x::(bubblesort xs))


mata
function bubble_sort(a) {
	n = length(a)
	for (j = n; j >= 2; j--) {
		q = 1
		for (i = 2; i <= j; i++) {
			if (a[i-1] > a[i]) {
				q = 0
				s = a[i-1]
				a[i-1] = a[i]
				a[i] = s
			}
		}
		if (q) return
	}
}
end


func bubbleSort<T:Comparable>(list:inout[T]) {
    var done = false
    while !done {
        done = true
        for i in 1..<list.count {
            if list[i - 1] > list[i] {
                (list[i], list[i - 1]) = (list[i - 1], list[i])
                done = false
            }
        }
    }
}

var list1 = [3, 1, 7, 5, 2, 5, 3, 8, 4]
print(list1)
bubbleSort(list: &list1)
print(list1)


x : 23 : 15 : 99 : 146 : 3 : 66 : 71 : 5 : 23 : 73 : 19

bubble_sort param index size

 + index size limit
lp
  changes
  - limit
  index i
  if i < limit
    + 1 i ip1
    if base.i > base.ip1
       swap base.i base.ip1
       + changes
    endif
    + i
    goif
  endif
 if changes > 0
    go lp
 endif
 return

start

 ' original values : ' $r
 call showvalues
 call bubble_sort @x #x
 ' sorted values : ' $r
 call showvalues
 stop

showvalues
 $s
 i
 if i < #x
    "$s ' ' x.i ' '" $s
    + i
    goif
 endif
 " $r $s " []
 return


templates bubblesort
  templates bubble
    @: 1;
    1..$-1 -> #
    [email protected] !
    when <?([email protected]($+1) <[email protected]($)>)> do
      @: $;
      def temp: [email protected]([email protected]);
      @bubblesort([email protected]): [email protected]([email protected]+1);
      @bubblesort([email protected]+1): $temp;
  end bubble

  @: $;
  $::length -> #
  [email protected] !

  when <2..> do
    $ -> bubble -> #
end bubblesort

[4,5,3,8,1,2,6,7,9,8,5] -> bubblesort -> !OUT::write


package require Tcl 8.5
package require struct::list

proc bubblesort {A} {
    set len [llength $A]
    set swapped true
    while {$swapped} {
        set swapped false
        for {set i 0} {$i < $len - 1} {incr i} {
            set j [expr {$i + 1}]
            if {[lindex $A $i] > [lindex $A $j]} {
                struct::list swap A $i $j
                set swapped true
            }
        }
        incr len -1
    }
    return $A
}

puts [bubblesort {8 6 4 2 1 3 5 7 9}] ;# => 1 2 3 4 5 6 7 8 9


:L1→L2
:1+dim(L2)→N
:For(D,1,dim(L2))
:N-1→N
:0→I
:For(C,1,dim(L2)-2)
:For(A,dim(L2)-N+1,dim(L2)-1)
:If L2(A)>L2(A+1)
:Then
:1→I
:L2(A)→B
:L2(A+1)→L2(A)
:B→L2(A+1)
:End
:End
:End
:If I=0
:Goto C
:End
:Lbl C
:If L2(1)>L2(2)
:Then
:L2(1)→B
:L2(2)→L2(1)
:B→L2(2)
:End
:DelVar A
:DelVar B
:DelVar C
:DelVar D
:DelVar N
:DelVar I
:Return


#! A simple Bubble Sort function
value| array count changed |
[ ( address count -- )
  to count to array
  count 0
  [ count 0
    [ i array array.get i 1 + array array.get 2dup >
      [ i array array.put  i 1 + array array.put ]
      [ 2drop ] ifTrueFalse
    ] countedLoop
    count 1 - to count
  ] countedLoop
] is bsort

#! Code to display an array
[ ( array count -- )
  0 swap [ dup i swap array.get . ] countedLoop drop cr
] is .array

#! Create a 10-cell array
10 cells is-array foo

#! Fill it with random values
  20  1 foo array.put
  50  2 foo array.put
 650  3 foo array.put
 120  4 foo array.put
 110  5 foo array.put
 101  6 foo array.put
1321  7 foo array.put
1310  8 foo array.put
 987  9 foo array.put
 10 10 foo array.put

#! Display the array, sort it, and display it again
foo 10 .array
foo 10 bsort
foo 10 .array


//Note that we're assuming that the list of numbers is separated by tabs.
function bubbleSort(%list)
{
	%ct = getFieldCount(%list);
	for(%i = 0; %i < %ct; %i++)
	{
		for(%k = 0; %k < (%ct - %i - 1); %k++)
		{
			if(getField(%list, %k) > getField(%list, %k+1))
			{
				%tmp = getField(%list, %k);
				%list = setField(%list, %k, getField(%list, %k+1));
				%list = setField(%list, %k+1, %tmp);
			}
		}
	}
	return %list;
}


PRINT "Bubble sort:"
  n = FUNC (_InitArray)
  PROC _ShowArray (n)
  PROC _Bubblesort (n)
  PROC _ShowArray (n)
PRINT

END

_Bubblesort PARAM(1)                   ' Bubble sort
  LOCAL (2)

  DO
    [email protected] = 0
    FOR [email protected] = 1 TO [email protected]
      IF @([email protected]) > @([email protected]) THEN PROC _Swap ([email protected], [email protected]) : [email protected] = [email protected]
    NEXT
    [email protected] = [email protected]
    UNTIL [email protected] = 0
  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


rm -f _sortpass

reset() {
   test -f _tosort || mv _sortpass _tosort
}

bpass() {
  (read a; read b
  test -n "$b" -a "$a" && (
      test $a -gt $b && (reset; echo $b;  (echo $a ; cat) | bpass ) || (echo $a;  (echo $b ; cat) | bpass )
  ) || echo $a)
}

bubblesort() {
  cat > _tosort
  while test -f _tosort
  do
      cat _tosort | (rm _tosort;cat) |bpass > _sortpass
  done
  cat _sortpass
}

cat to.sort | bubblesort


#import nat

bubblesort "p" = @iNX ^=T ^llPrEZryPrzPlrPCXlQ/~& @l ~&aitB^?\~&a "p"?ahthPX/~&ahPfatPRC ~&ath2fahttPCPRC

#cast %nL

example = bubblesort(nleq) <362,212,449,270,677,247,567,532,140,315>


void swap(int[] array, int i1, int i2) {
  if (array[i1] == array[i2])
    return;
  var tmp = array[i1];
  array[i1] = array[i2];
  array[i2] = tmp;
}

void bubble_sort(int[] array) {
  bool flag = true;
  int j = array.length;
  while(flag) {
    flag = false;
    for (int i = 1; i < j; i++) {
      if (array[i] < array[i - 1]) {
        swap(array, i - 1, i);
        flag = true;
      }
    }
    j--;
  }
}

void main() {
  int[] array = {5, -1, 101, -4, 0, 1, 8, 6, 2, 3};
  bubble_sort(array);
  foreach (int i in array)
    print("%d ", i);
}


Private Function bubble_sort(s As Variant) As Variant
    Dim tmp As Variant
    Dim changed As Boolean
    For j = UBound(s) To 1 Step -1
        changed = False
        For i = 1 To j - 1
            If s(i) > s(i + 1) Then
                tmp = s(i)
                s(i) = s(i + 1)
                s(i + 1) = tmp
                changed = True
            End If
        Next i
        If Not changed Then
            Exit For
        End If
    Next j
    bubble_sort = s
End Function

Public Sub main()
    s = [{4, 15, "delta", 2, -31, 0, "alfa", 19, "gamma", 2, 13, "beta", 782, 1}]
    Debug.Print "Before: "
    Debug.Print Join(s, ", ")
    Debug.Print "After: "
    Debug.Print Join(bubble_sort(s), ", ")
End Sub


sub decr( byref n )
	n = n - 1
end sub

sub incr( byref n )
	n = n + 1
end sub

sub swap( byref a, byref b)
	dim tmp
	tmp = a
	a = b
	b = tmp
end sub

function bubbleSort( a )
	dim changed
	dim itemCount
	itemCount = ubound(a)
	do
		changed = false
		decr itemCount
		for i = 0 to itemCount
			if a(i) > a(i+1) then
				swap a(i), a(i+1)
				changed = true
			end if
		next
	loop until not changed
	bubbleSort = a
end function


ARRAY INTEGER($nums;0)
APPEND TO ARRAY($nums;2)
APPEND TO ARRAY($nums;4)
APPEND TO ARRAY($nums;3)
APPEND TO ARRAY($nums;1)
APPEND TO ARRAY($nums;2)
SORT ARRAY($nums)  ` sort in ascending order
SORT ARRAY($nums;<)  ` sort in descending order


/* ARM assembly AARCH64 Raspberry PI 3B */
/*  program integerSort64.s  with selection sort  */

/*******************************************/
/* Constantes file                         */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeConstantesARM64.inc"

/*********************************/
/* Initialized data              */
/*********************************/
.data
szMessSortOk:       .asciz "Table sorted.\n"
szMessSortNok:      .asciz "Table not sorted !!!!!.\n"
sMessResult:        .asciz "Value  : @ \n"
szCarriageReturn:   .asciz "\n"

.align 4
#TableNumber:      .quad   1,3,6,2,5,9,10,8,4,7
TableNumber:     .quad   10,9,8,7,6,5,4,3,2,1
                 .equ NBELEMENTS, (. - TableNumber) / 8
/*********************************/
/* UnInitialized data            */
/*********************************/
.bss
sZoneConv:       .skip 24
/*********************************/
/*  code section                 */
/*********************************/
.text
.global main
main:                                              // entry of program
    ldr x0,qAdrTableNumber                         // address number table
    mov x1,0
    mov x2,NBELEMENTS                              // number of élements
    bl selectionSort
    ldr x0,qAdrTableNumber                         // address number table
    bl displayTable

    ldr x0,qAdrTableNumber                         // address number table
    mov x1,NBELEMENTS                              // number of élements
    bl isSorted                                    // control sort
    cmp x0,1                                       // sorted ?
    beq 1f
    ldr x0,qAdrszMessSortNok                       // no !! error sort
    bl affichageMess
    b 100f
1:                                                 // yes
    ldr x0,qAdrszMessSortOk
    bl affichageMess
100:                                               // standard end of the program
    mov x0,0                                       // return code
    mov x8,EXIT                                    // request to exit program
    svc 0                                          // perform the system call

qAdrsZoneConv:            .quad sZoneConv
qAdrszCarriageReturn:     .quad szCarriageReturn
qAdrsMessResult:          .quad sMessResult
qAdrTableNumber:          .quad TableNumber
qAdrszMessSortOk:         .quad szMessSortOk
qAdrszMessSortNok:        .quad szMessSortNok
/******************************************************************/
/*     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]
1:
    add x2,x2,1
    cmp x2,x1
    bge 99f
    ldr x3,[x0,x2, lsl 3]
    cmp x3,x4
    blt 98f
    mov x4,x3
    b 1b
98:
    mov x0,0                       // not sorted
    b 100f
99:
    mov x0,1                       // sorted
100:
    ldp x3,x4,[sp],16              // restaur  2 registers
    ldp x2,lr,[sp],16              // restaur  2 registers
    ret                            // return to address lr x30
/******************************************************************/
/*         selection sort                                              */
/******************************************************************/
/* x0 contains the address of table */
/* x1 contains the first element    */
/* x2 contains the number of element */
selectionSort:
    stp x1,lr,[sp,-16]!              // save  registers
    stp x2,x3,[sp,-16]!              // save  registers
    stp x4,x5,[sp,-16]!              // save  registers
    stp x6,x7,[sp,-16]!              // save  registers
    mov x3,x1                        // start index i
    sub x7,x2,1                      // compute n - 1
1:                                   // start loop
    mov x4,x3
    add x5,x3,1                      // init index 2
2:
    ldr x1,[x0,x4,lsl 3]             // load value A[mini]
    ldr x6,[x0,x5,lsl 3]             // load value A[j]
    cmp x6,x1                        // compare value
    csel x4,x5,x4,lt                 // j -> mini
    add x5,x5,1                      // increment index j
    cmp x5,x2                        // end ?
    blt 2b                           // no -> loop
    cmp x4,x3                        // mini <> j ?
    beq 3f                           // no
    ldr x1,[x0,x4,lsl 3]             // yes swap A[i] A[mini]
    ldr x6,[x0,x3,lsl 3]
    str x1,[x0,x3,lsl 3]
    str x6,[x0,x4,lsl 3]
3:
    add x3,x3,1                      // increment i
    cmp x3,x7                        // end ?
    blt 1b                           // no -> loop

100:
    ldp x6,x7,[sp],16                // restaur  2 registers
    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

/******************************************************************/
/*      Display table elements                                */
/******************************************************************/
/* x0 contains the address of table */
displayTable:
    stp x1,lr,[sp,-16]!              // save  registers
    stp x2,x3,[sp,-16]!              // save  registers
    mov x2,x0                        // table address
    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
    bl strInsertAtCharInc            // insert result at @ character
    bl affichageMess                 // display message
    add x3,x3,1
    cmp x3,NBELEMENTS - 1
    ble 1b
    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
/********************************************************/
/*        File Include fonctions                        */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"


INCLUDE "D2:SORT.ACT" ;from the Action! Tool Kit

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 Test(INT ARRAY a INT size BYTE order)
  PrintE("Array before sort:")
  PrintArray(a,size)
  SortI(a,size,order)
  PrintE("Array after sort:")
  PrintArray(a,size)
  PutE()
RETURN

PROC Main()
  DEFINE ASCENDING="0"
  INT ARRAY
    a(10)=[1 4 65535 0 3 7 4 8 20 65530],
    b(21)=[10 9 8 7 6 5 4 3 2 1 0
      65535 65534 65533 65532 65531
      65530 65529 65528 65527 65526],
    c(8)=[101 102 103 104 105 106 107 108],
    d(12)=[1 65535 1 65535 1 65535 1
      65535 1 65535 1 65535]

  Put(125) PutE() ;clear screen
  Test(a,10,ASCENDING)
  Test(b,21,ASCENDING)
  Test(c,8,ASCENDING)
  Test(d,12,ASCENDING)
RETURN


Do Until NoMoreSwaps = True
     NoMoreSwaps = True
     For Counter = 1 To (NumberOfItems - 1)
         If List(Counter) > List(Counter + 1) Then
             NoMoreSwaps = False
             Temp = List(Counter)
             List(Counter) = List(Counter + 1)
             List(Counter + 1) = Temp
         End If
     Next
     NumberOfItems = NumberOfItems - 1
Loop


fn bubble(mut arr []int) {
        println('Input: ${arr.str()}')
        mut count := arr.len
        for {
                if count <= 1 {
                        break
                }
                mut has_changed := false
                count--
                for i := 0; i < count; i++ {
                        if arr[i] > arr[i + 1] {
                                temp := arr[i + 1]
                                arr[i + 1] = arr[i]
                                arr[i] = temp
                                has_changed = true
                        }
                }
                if !has_changed {
                        break
                }
        }
        println('Output: ${arr.str()}')
}

fn main() {
        mut arr := [3, 5, 2, 1, 4]
        bubble(mut arr)
}


//Comparison function must returns Numbers even though it deals with integers.
function compare(x:int, y:int):Number
{
	return Number(x-y);
}
var nums:Vector.<int> = Vector.<int>([5,12,3,612,31,523,1,234,2]);
nums.sort(compare);


with Gnat.Heap_Sort_G;

procedure Integer_Sort is
   -- Heap sort package requires data to be in index values starting at
   -- 1 while index value 0 is used as temporary storage
   type Int_Array is array(Natural range <>) of Integer;
   Values : Int_Array := (0,1,8,2,7,3,6,4,5);

   -- define move and less than subprograms for use by the heap sort package
   procedure Move_Int(From : Natural; To : Natural) is
   begin
      Values(To) := Values(From);
   end Move_Int;

   function Lt_Int(Left, Right : Natural) return Boolean is
   begin
      return Values(Left) < Values (Right);
   end Lt_Int;

   -- Instantiate the generic heap sort package
   package Heap_Sort is new Gnat.Heap_Sort_G(Move_Int, Lt_Int);

begin
   Heap_Sort.Sort(8);
end Integer_Sort;

requires an Ada05 compiler, e.g GNAT GPL 2007
with Ada.Containers.Generic_Array_Sort;

procedure Integer_Sort is
   --
   type Int_Array is array(Natural range <>) of Integer;
   Values : Int_Array := (0,1,8,2,7,3,6,4,5);

   -- Instantiate the generic sort package from the standard Ada library
   procedure Sort is new Ada.Containers.Generic_Array_Sort
     (Index_Type   => Natural,
      Element_Type => Integer,
      Array_Type   => Int_Array);

begin
   Sort(Values);
end Integer_Sort;


var bubbleSort = Fn.new { |a|
    var n = a.count
    if (n < 2) return
    while (true) {
        var swapped = false
        for (i in 1..n-1) {
            if (a[i-1] > a[i]) {
                var t = a[i-1]
                a[i-1] = a[i]
                a[i] = t
                swapped = true
            }
        }
        if (!swapped) return
    }
}

var as = [ [4, 65, 2, -31, 0, 99, 2, 83, 782, 1], [7, 5, 2, 6, 1, 4, 2, 6, 3] ]
for (a in as) {
    System.print("Before: %(a)")
    bubbleSort.call(a)
    System.print("After : %(a)")
    System.print()
}


        .model  tiny
        .code
        .486
        org     100h
start:  mov     si, offset array
        mov     ax, 40          ;length of array (not including $)
        call    bsort
        mov     dx, si          ;point to array
        mov     ah, 09h         ;display it as a string
        int     21h
        ret
array   db      "Pack my box with five dozen liquor jugs.$"

;Bubble sort: si = array addrsss, ax = number of bytes
bsort:  pusha
        xchg    cx, ax          ;get size of array N
        dec     cx              ;for J:= N-1 downto 0
bs10:   xor     bx, bx          ;for I:= 0 to J-1
bs20:   mov     ax, [bx+si]
        cmp     al, ah          ;if A(I) > A(I+1) then
        jbe     bs30
         xchg   al, ah          ; swap bytes
         mov    [bx+si], ax
bs30:   inc     bx              ;next I
        cmp     bx, cx
        jb      bs20
        loop    bs10
        popa
        ret
        end     start


CO PR READ "shell_sort.a68" PR CO
MODE TYPE = INT;

PROC in place shell sort = (REF[]TYPE seq)REF[]TYPE:(
    INT inc := ( UPB seq + LWB seq + 1 ) OVER 2;
    WHILE inc NE 0 DO
        FOR index FROM LWB seq TO UPB seq DO
            INT i := index;
            TYPE el = seq[i];
            WHILE ( i  - LWB seq >= inc | seq[i - inc] > el | FALSE ) DO
                seq[i] := seq[i - inc];
                i -:= inc
            OD;
            seq[i] := el
        OD;
        inc := IF inc = 2 THEN 1 ELSE ENTIER(inc * 5 / 11) FI
    OD;
    seq
);

PROC shell sort = ([]TYPE seq)[]TYPE:
  in place shell sort(LOC[LWB seq: UPB seq]TYPE:=seq);

print((shell sort((2, 4, 3, 1, 2)), new line))


begin
    % use the quicksort procedure from the Sorting_Algorithms/Quicksort task %
    % Quicksorts in-place the array of integers v, from lb to ub - external  %
    procedure quicksort ( integer array v( * )
                        ; integer value lb, ub
                        ) ; algol "sortingAlgorithms_Quicksort" ;
    % sort an integer array with the quicksort routine                       %
    begin
        integer array t ( 1 :: 5 );
        integer p;
        p := 1;
        for v := 2, 3, 1, 9, -2 do begin t( p ) := v; p := p + 1; end;
        quicksort( t, 1, 5 );
        for i := 1 until 5 do writeon( i_w := 1, s_w := 1, t( i ) )
    end
end.


Dim temp, count As Integer
Dim isDirty As Boolean
count = Ubound(list) // count the array size

// loop through until we don't move any numbers... this means we are sorted
Do
  isDirty = False // we haven't touched anything yet
  For i As Integer = 1 To count - 1 // loop through all the numbers
    If list(i) > list(i + 1) Then // if the right number is smaller then the left.. swap
      temp = list(i + 1)
      list(i + 1) = list(i)
      list(i) = temp
      isDirty = True // we touched the data so mark it as dirty
    End
  Next
Loop Until isDirty = False // if we made it without touching the data then we are done


include c:\cxpl\codes;          \intrinsic 'code' declarations
string 0;                       \use zero-terminated strings

proc    BSort(A, N);            \Bubble sort array in ascending order
char    A;                      \address of array
int     N;                      \number of items in array (size)
int     I, J, T;
[for J:= N-1 downto 0 do
    for I:= 0 to J-1 do
        if A(I) > A(I+1) then
            [T:= A(I);  A(I):= A(I+1);  A(I+1):= T];    \swap items
];      \BSort

func    StrLen(Str);            \Return number of characters in an ASCIIZ string
char    Str;
int     I;
for I:= 0 to -1>>1-1 do
        if Str(I) = 0 then return I;

char    Str;
[Str:= "Pack my box with five dozen liquor jugs.";
BSort(Str, StrLen(Str));
Text(0, Str);  CrLf(0);
]


// Animated sort.
// Original idea by William Tang, obtained from MicroHobby 25 Years (https://microhobby.speccy.cz/zxsf/MH-25Years.pdf)

clear screen

n=15 : m=18 : y=9 : t$=chr$(17)+chr$(205)+chr$(205)
dim p(n), p$(n)

for x=1 TO n
    p(x)=ran(15)+1
    p$(x)=str$(p(x),"##.######")
    print at(0,x) p$(x)
next x

for j=1 to n-1
    for i=j+1 to n
        l=n+j-i+1
        if p(j) > p(l) then
            print color("yellow","red") at(0,j) p$(j)
            if l<>m then
                for x=m to l step sig(l-m): print at(18,x) t$ : print at (18,x+sig(m-l)) "   " : pause .02 : next x
            end if
            for x=17 TO y step -1 : print at(x,l) t$+" " : pause .02 : next x
            for x=0 TO 10 : print at(x,l) " "+p$(l)+t$ : pause .02 : next x
            for x=l TO j STEP -1 : print at(11,x) p$(l)+t$ : print at(11,x+1) "            " : pause .02 : next x
            print at(0,j) "            "
            for x=j+1 TO l-1 : print color("yellow","red") at(0,x) p$(j) : pause .02 : print at(0,x) p$(x) : pause .02 : next x
            print at(0,l) p$(j)
            for x=10 TO 0 step -1 : print at(x,j) p$(l)+t$+" " : pause .02 : next x
            for x=y TO 17 : print at(x,j) " "+t$ : pause .02 : next x
            m=j
            t=p(l) : tem$=p$(l)
            p(l)=p(j) : p$(l)=p$(j)
            p(j)=t : p$(j)=tem$
        end if
        pause .02
    next i
next j

for x=m TO 18 : print at(18,x-1) "   " : print at(18,x) t$ : pause .02 : next x


use framework "Foundation"

-- sort :: [a] -> [a]
on sort(lst)
    ((current application's NSArray's arrayWithArray:lst)'s ¬
        sortedArrayUsingSelector:"compare:") as list
end sort

-- TEST -----------------------------------------------------------------------
on run

    map(sort, [[9, 1, 8, 2, 8, 3, 7, 0, 4, 6, 5], ¬
        ["alpha", "beta", "gamma", "delta", "epsilon", "zeta", "eta", ¬
            "theta", "iota", "kappa", "lambda", "mu"]])

end run

-- GENERIC FUNCTIONS  ---------------------------------------------------------

-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
    tell mReturn(f)
        set lng to length of xs
        set lst to {}
        repeat with i from 1 to lng
            set end of lst to |λ|(item i of xs, i, xs)
        end repeat
        return lst
    end tell
end map

-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: Handler -> Script
on mReturn(f)
    if class of f is script then
        f
    else
        script
            property |λ| : f
        end script
    end if
end mReturn


/* ARM assembly Raspberry PI  */
/*  program integerSort.s  with selection sort */

 /* REMARK 1 : this program use routines in a include file
   see task Include a file language arm assembly
   for the routine affichageMess conversion10
   see at end of this program the instruction include */
/* for constantes see task include a file in arm assembly */
/************************************/
/* Constantes                       */
/************************************/
.include "../constantes.inc"

/*********************************/
/* Initialized data              */
/*********************************/
.data
szMessSortOk:       .asciz "Table sorted.\n"
szMessSortNok:      .asciz "Table not sorted !!!!!.\n"
sMessResult:        .asciz "Value  : @ \n"
szCarriageReturn:   .asciz "\n"

.align 4
TableNumber:      .int   1,3,6,2,5,9,10,8,4,7
#TableNumber:     .int   10,9,8,7,6,5,4,3,2,1
                 .equ NBELEMENTS, (. - TableNumber) / 4
/*********************************/
/* UnInitialized data            */
/*********************************/
.bss
sZoneConv:            .skip 24
/*********************************/
/*  code section                 */
/*********************************/
.text
.global main
main:                                              @ entry of program

1:
    ldr r0,iAdrTableNumber                         @ address number table
    mov r1,#0
    mov r2,#NBELEMENTS                             @ number of élements
    bl selectionSort
    ldr r0,iAdrTableNumber                         @ address number table
    bl displayTable

    ldr r0,iAdrTableNumber                         @ address number table
    mov r1,#NBELEMENTS                             @ number of élements
    bl isSorted                                    @ control sort
    cmp r0,#1                                      @ sorted ?
    beq 2f
    ldr r0,iAdrszMessSortNok                       @ no !! error sort
    bl affichageMess
    b 100f
2:                                                 @ yes
    ldr r0,iAdrszMessSortOk
    bl affichageMess
100:                                               @ standard end of the program
    mov r0, #0                                     @ return code
    mov r7, #EXIT                                  @ request to exit program
    svc #0                                         @ perform the system call

iAdrszCarriageReturn:     .int szCarriageReturn
iAdrsMessResult:          .int sMessResult
iAdrTableNumber:          .int TableNumber
iAdrszMessSortOk:         .int szMessSortOk
iAdrszMessSortNok:        .int szMessSortNok
/******************************************************************/
/*     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
/******************************************************************/
/*         selection sort                                              */
/******************************************************************/
/* r0 contains the address of table */
/* r1 contains the first element    */
/* r2 contains the number of element */
selectionSort:
    push {r1-r7,lr}                                        @ save registers
    mov r3,r1                                              @ start index i
    sub r7,r2,#1                                           @ compute n - 1
1:                                                         @ start loop
    mov r4,r3
    add r5,r3,#1                                           @ init index 2
2:
    ldr r1,[r0,r4,lsl #2]                                  @ load value A[mini]
    ldr r6,[r0,r5,lsl #2]                                  @ load value A[j]
    cmp r6,r1                                              @ compare value
    movlt r4,r5                                            @ j -> mini
    add r5,#1                                              @ increment index j
    cmp r5,r2                                              @ end ?
    blt 2b                                                 @ no -> loop
    cmp r4,r3                                              @ mini <> j ?
    beq 3f                                                 @ no
    ldr r1,[r0,r4,lsl #2]                                  @ yes swap A[i] A[mini]
    ldr r6,[r0,r3,lsl #2]
    str r1,[r0,r3,lsl #2]
    str r6,[r0,r4,lsl #2]
3:
    add r3,#1                                              @ increment i
    cmp r3,r7                                              @ end ?
    blt 1b                                                 @ no -> loop

100:
    pop {r1-r7,lr}
    bx lr                                                  @ return

/******************************************************************/
/*      Display table elements                                */
/******************************************************************/
/* r0 contains the address of table */
displayTable:
    push {r0-r3,lr}                                    @ save registers
    mov r2,r0                                          @ table address
    mov r3,#0
1:                                                     @ loop display table
    ldr r0,[r2,r3,lsl #2]
    ldr r1,iAdrsZoneConv                               @
    bl conversion10                                    @ décimal conversion
    ldr r0,iAdrsMessResult
    ldr r1,iAdrsZoneConv                               @ insert conversion
    bl strInsertAtCharInc
    bl affichageMess                                   @ display message
    add r3,#1
    cmp r3,#NBELEMENTS - 1
    ble 1b
    ldr r0,iAdrszCarriageReturn
    bl affichageMess
100:
    pop {r0-r3,lr}
    bx lr
iAdrsZoneConv:           .int sZoneConv
/***************************************************/
/*      ROUTINES INCLUDE                           */
/***************************************************/
.include "../affichage.inc"


func bubblesort(&items) {
  itemCount = numberof(items);
  do {
    hasChanged = 0;
    itemCount--;
    for(index = 1; index <= itemCount; index++) {
      if(items(index) > items(index+1)) {
        items([index,index+1]) = items([index+1,index]);
        hasChanged = 1;
      }
    }
  } while(hasChanged);
}


fcn bubbleSort(list){
   itemCount := list.len();
   do{
      hasChanged := False;
      foreach index in (itemCount -= 1){
	 if (list[index] > list[index + 1]){
	    list.swap(index,index + 1);
	    hasChanged = True;
	 }
      }
   }while(hasChanged);
   list
}


arr: [2 3 5 8 4 1 6 9 7]
sort 'arr ; in-place

loop arr => print


numbers = 5 4 1 2 3
sort, numbers, N D%A_Space%
Msgbox % numbers


# syntax: GAWK -f SORT_AN_INTEGER_ARRAY.AWK
BEGIN {
    split("9,10,3,1234,99,1,200,2,0,-2",arr,",")
    show("@unsorted","unsorted")
    show("@val_num_asc","sorted ascending")
    show("@val_num_desc","sorted descending")
    exit(0)
}
function show(sequence,description,  i) {
    PROCINFO["sorted_in"] = sequence
    for (i in arr) {
      printf("%s ",arr[i])
    }
    printf("\t%s\n",description)
}


5000 CLS
5002 LET a$="": FOR f=1 TO 64: LET a$=a$+CHR$ (32+INT (RND*96)): NEXT f
5004 PRINT a$; AT 10,0;"ZigZag BubbleSORT"
5010 LET la=LEN a$
5011 LET i=1: LET u=0
5020 LET d=0: LET p=(u=0)-(u=1)
5021 LET l=(i AND u=0)+(la-i+u AND u=1)
5030 IF u=0 THEN  IF a$(l+1)>=a$(l) THEN  GO TO 5050
5031 IF u=1 THEN  IF a$(l-1)<=a$(l) THEN  GO TO 5050
5040 LET d=1
5042 LET t$=a$(l+p)
5043 LET a$(l+p)=a$(l)
5044 LET a$(l)=t$
5050 LET l=l+p
5051 PRINT AT 10,21;a$(l);AT 12,0;a$
5055 IF l<=la-i AND l>=i THEN  GO TO 5023
5061 LET i=i+NOT u
5063 LET u=NOT u
5064 IF d AND i<la THEN  GO TO 5020
5072 PRINT AT 12,0;a$
9000 STOP


babel> nil { zap {1 randlf 100 rem} 20 times collect ! } nest dup lsnum ! --> Create a list of random numbers
( 20 47 69 71 18 10 92 9 56 68 71 92 45 92 12 7 59 55 54 24 )
babel> ls2lf                                                              --> Convert list to array for sorting
babel> dup {fnord} merge_sort                                             --> The internal sort operator
babel> ar2ls lsnum !                                                      --> Display the results
( 7 9 10 12 18 20 24 45 47 54 55 56 59 68 69 71 71 92 92 92 )


' Sort an integer array
DECLARE values[5] TYPE NUMBER
values[0] = 23
values[1] = 32
values[2] = 12
values[3] = 21
values[4] = 01

SORT values

FOR i = 0 TO 3
    PRINT values[i], ", ";
NEXT
PRINT values[4]


      INSTALL @lib$+"SORTLIB"
      sort% = FN_sortinit(0,0)

      DIM array(8)
      array() = 8, 2, 5, 9, 1, 3, 6, 7, 4

      C% = DIM(array(),1) + 1
      CALL sort%, array(0)

      FOR i% = 0 TO DIM(array(),1) - 1
        PRINT ; array(i%) ", ";
      NEXT
      PRINT ; array(i%)


beads 1 program 'Sort an integer array'
calc main_init
	var arr = [4, 1, 2, -1, 3, 0, 2]
	var newarr : array of num
	loop across:arr sort:val count:c val:v
		newarr[c] = v


#include <stdlib.h>  /* qsort() */
#include <stdio.h>   /* printf() */

int intcmp(const void *aa, const void *bb)
{
    const int *a = aa, *b = bb;
    return (*a < *b) ? -1 : (*a > *b);
}

int main()
{
    int nums[5] = {2,4,3,1,2};
    qsort(nums, 5, sizeof(int), intcmp);
    printf("result: %d %d %d %d %d\n",
      nums[0], nums[1], nums[2], nums[3], nums[4]);
    return 0;
}


using System;
using System.Collections.Generic;

public class Program {
    static void Main() {
        int[] unsorted = { 6, 2, 7, 8, 3, 1, 10, 5, 4, 9 };
        Array.Sort(unsorted);
    }
}


#include <algorithm>

int main()
{
    int nums[] = {2,4,3,1,2};
    std::sort(nums, nums+sizeof(nums)/sizeof(int));
    return 0;
}


import StdEnv

sortArray :: (a e) -> a e | Array a e & Ord e
sortArray array = {y \\ y <- sort [x \\ x <-: array]}

Start :: {#Int}
Start = sortArray {2, 4, 3, 1, 2}


DEFINE PTR="CARD"

PROC PrintArray(PTR ARRAY a INT size)
  INT i

  FOR i=0 TO size-1
  DO
    PrintE(a(i))
  OD
RETURN

INT FUNC Decode(CHAR ARRAY s INT ARRAY a)
  INT count
  BYTE i,begin,end
  CHAR ARRAY tmp(10)

  count=0 i=1
  WHILE i<=s(0)
  DO
    begin=i
    WHILE i<=s(0) AND s(i)#'.
    DO i==+1 OD
    end=i-1
    IF i<s(0) THEN i==+1 FI
    SCopyS(tmp,s,begin,end)
    a(count)=ValI(tmp)
    count==+1
  OD
RETURN (count)

INT FUNC Compare(CHAR ARRAY s1,s2)
  INT ARRAY a1(20),a2(20)
  INT c1,c2,res
  BYTE i

  c1=Decode(s1,a1)
  c2=Decode(s2,a2)

  i=0
  DO
    IF i=c1 AND i=c2 THEN
      RETURN (0)
    ELSEIF i=c1 THEN
      RETURN (-1)
    ELSEIF i=c2 THEN
      RETURN (1)
    FI

    IF a1(i)<a2(i) THEN
      RETURN (-1)
    ELSEIF a1(i)>a2(i) THEN
      RETURN (1)
    FI
    i==+1
  OD
RETURN (0)

PROC Sort(PTR ARRAY a INT size)
  INT i,j,minpos
  CHAR ARRAY tmp

  FOR i=0 TO size-2
  DO
    minpos=i
    FOR j=i+1 TO size-1
    DO
      IF Compare(a(minpos),a(j))>0 THEN
        minpos=j
      FI
    OD

    IF minpos#i THEN
      tmp=a(i)
      a(i)=a(minpos)
      a(minpos)=tmp
    FI
  OD
RETURN

PROC Main()
  DEFINE SIZE="6"
  PTR ARRAY a(SIZE)

  a(0)="1.3.6.1.4.1.11.2.17.19.3.4.0.10"
  a(1)="1.3.6.1.4.1.11.2.17.5.2.0.79"
  a(2)="1.3.6.1.4.1.11.2.17.19.3.4.0.4"
  a(3)="1.3.6.1.4.1.11150.3.4.0.1"
  a(4)="1.3.6.1.4.1.11.2.17.19.3.4.0.1"
  a(5)="1.3.6.1.4.1.11150.3.4.0"

  PrintE("Array before sort:")
  PrintArray(a,SIZE) PutE()

  Sort(a,SIZE)
  PrintE("Array after sort:")
  PrintArray(a,SIZE)
RETURN


with Ada.Containers.Generic_Array_Sort;
with Ada.Strings.Fixed;
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
with Ada.Text_IO;
with Ada.Unchecked_Deallocation;

procedure Sort_List_Identifiers is
   type Natural_Array is array (Positive range <>) of Natural;
   type Unbounded_String_Array is array(Positive range <>) of Unbounded_String;

   function To_Natural_Array(input : in String) return Natural_Array
   is
      target : Natural_Array(1 .. Ada.Strings.Fixed.Count(input, ".") + 1);
      from : Natural := input'First;
      to : Natural := Ada.Strings.Fixed.Index(input, ".");
      index : Positive := target'First;
   begin
      while to /= 0 loop
         target(index) := Natural'Value(input(from .. to - 1));
         from := to + 1;
         index := index + 1;
         to := Ada.Strings.Fixed.Index(input, ".", from);
      end loop;
      target(index) := Natural'Value(input(from .. input'Last));
      return target;
   end To_Natural_Array;

   function Lesser(Left, Right : in Unbounded_String) return Boolean is
   begin
      return To_Natural_Array(To_String(Left)) < To_Natural_Array(To_String(Right));
   end Lesser;

   procedure Sort is new Ada.Containers.Generic_Array_Sort
     (Index_Type   => Positive,
      Element_Type => Unbounded_String,
      Array_Type   => Unbounded_String_Array,
      "<"          => Lesser);

   table : Unbounded_String_Array :=
     (To_Unbounded_String("1.3.6.1.4.1.11.2.17.19.3.4.0.10"),
      To_Unbounded_String("1.3.6.1.4.1.11.2.17.5.2.0.79"),
      To_Unbounded_String("1.3.6.1.4.1.11.2.17.19.3.4.0.4"),
      To_Unbounded_String("1.3.6.1.4.1.11150.3.4.0.1"),
      To_Unbounded_String("1.3.6.1.4.1.11.2.17.19.3.4.0.1"),
      To_Unbounded_String("1.3.6.1.4.1.11150.3.4.0"));
begin
   Sort(table);
   for element of table loop
      Ada.Text_IO.Put_Line(To_String(element));
   end loop;
end Sort_List_Identifiers;


(* Shell sort
Algorithm: Donald Shell, 1959.
*)

on ShellSort(theList, l, r)
    script o
        property lst : theList
    end script

    set listLength to (count theList)
    if (listLength > 1) then
        -- Convert negative and/or transposed range indices.
        if (l < 0) then set l to listLength + l + 1
        if (r < 0) then set r to listLength + r + 1
        if (l > r) then set {l, r} to {r, l}

        -- Do the sort.
        set stepSize to (r - l + 1) div 2
        repeat while (stepSize > 0)
            repeat with i from (l + stepSize) to r
                set currentValue to item i of o's lst
                repeat with j from (i - stepSize) to l by -stepSize
                    set thisValue to item j of o's lst
                    if (currentValue < thisValue) then
                        set item (j + stepSize) of o's lst to thisValue
                    else
                        set j to j + stepSize
                        exit repeat
                    end if
                end repeat
                if (j < i) then set item j of o's lst to currentValue
            end repeat
            set stepSize to (stepSize / 2.2) as integer
        end repeat
    end if

    return -- nothing. The input list has been sorted in place.
end ShellSort
property sort : ShellSort

-- Test code: sort items 1 thru -1 (ie. all) of a list of strings, treating numeric portions numerically.
set theList to {"1.3.6.1.4.1.11.2.17.19.3.4.0.10", "1.3.6.1.4.1.11.2.17.5.2.0.79", "1.3.6.1.4.1.11.2.17.19.3.4.0.4", ¬
    "1.3.6.1.4.1.11150.3.4.0.1", "1.3.6.1.4.1.11.2.17.19.3.4.0.1", "1.3.6.1.4.1.11150.3.4.0"}
considering numeric strings
    sort(theList, 1, -1)
end considering
return theList


(sort [5 4 3 2 1]) ; sort can also take a comparator function
(1 2 3 4 5)


       PROGRAM-ID. sort-ints.

       DATA DIVISION.
       WORKING-STORAGE SECTION.
       01  array-area             VALUE "54321".
           03  array              PIC 9 OCCURS 5 TIMES.
       01  i                      PIC 9.

       PROCEDURE DIVISION.
       main-line.
           PERFORM display-array
           SORT array ASCENDING array
           PERFORM display-array

           GOBACK
           .
       display-array.
           PERFORM VARYING i FROM 1 BY 1 UNTIL 5 < i
               DISPLAY array (i) " " NO ADVANCING
           END-PERFORM
           DISPLAY SPACE
           .


; based on http://www.rosettacode.org/wiki/Sorting_algorithms/Quicksort#AutoHotkey
OidQuickSort(a, Delim:=".", index:=1){
    if (a.Count() <= 1)
        return a
    Less := [], Equal := [], More := []
    Pivot := StrSplit(a[1], Delim)[index]
    for k, v in a
    {
        x := StrSplit(v, Delim)[index]
        if (x < Pivot)
            less.InsertAt(1, v)
        else if (x > Pivot)
            more.InsertAt(1, v)
        else
            Equal.InsertAt(1, v)
    }
    Equal := OidQuickSort(Equal, Delim, index+1)
    Less  := OidQuickSort(Less)
    Out	  := OidQuickSort(More)
    if (Equal.Count())
        Out.InsertAt(1, Equal*)	; InsertAt all values of Equal at index 1
    if (Less.Count())
        Out.InsertAt(1, Less*)	; InsertAt all values of Less at index 1
    return Out
}


# syntax: GAWK -f SORT_A_LIST_OF_OBJECT_IDENTIFIERS.AWK
#
# sorting:
#   PROCINFO["sorted_in"] is used by GAWK
#   SORTTYPE is used by Thompson Automation's TAWK
#
BEGIN {
    width = 10
    oid_arr[++n] = "1.3.6.1.4.1.11.2.17.19.3.4.0.10"
    oid_arr[++n] = "1.3.6.1.4.1.11.2.17.5.2.0.79"
    oid_arr[++n] = "1.3.6.1.4.1.11.2.17.19.3.4.0.4"
    oid_arr[++n] = "1.3.6.1.4.1.11150.3.4.0.1"
    oid_arr[++n] = "1.3.6.1.4.1.11.2.17.19.3.4.0.1"
    oid_arr[++n] = "1.3.6.1.4.1.11150.3.4.0"
#   oid_arr[++n] = "1.11111111111.1" # un-comment to test error
    for (i=1; i<=n; i++) {
      str = ""
      for (j=1; j<=split(oid_arr[i],arr2,"."); j++) {
        str = sprintf("%s%*s.",str,width,arr2[j])
        if ((leng = length(arr2[j])) > width) {
          printf("error: increase sort key width from %d to %d for entry %s\n",width,leng,oid_arr[i])
          exit(1)
        }
      }
      arr3[str] = ""
    }
    PROCINFO["sorted_in"] = "@ind_str_asc" ; SORTTYPE = 1
    for (i in arr3) {
      str = i
      gsub(/ /,"",str)
      sub(/\.$/,"",str)
      printf("%s\n",str)
    }
    exit(0)
}


import std.stdio, std.algorithm;

void main() {
    auto data = [2, 4, 3, 1, 2];
    data.sort(); // in-place
    assert(data == [1, 2, 2, 3, 4]);
}


uses Types, Generics.Collections;

var
  a: TIntegerDynArray;
begin
  a := TIntegerDynArray.Create(5, 4, 3, 2, 1);
  TArray.Sort<Integer>(a);
end;


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

typedef struct oid_tag {
    char* str_;
    int* numbers_;
    int length_;
} oid;

// free memory, no-op if p is null
void oid_destroy(oid* p) {
    if (p != 0) {
        free(p->str_);
        free(p->numbers_);
        free(p);
    }
}

int char_count(const char* str, char ch) {
    int count = 0;
    for (const char* p = str; *p; ++p) {
        if (*p == ch)
            ++count;
    }
    return count;
}

// construct an OID from a string
// returns 0 on memory allocation failure or parse error
oid* oid_create(const char* str) {
    oid* ptr = calloc(1, sizeof(oid));
    if (ptr == 0)
        return 0;
    ptr->str_ = strdup(str);
    if (ptr->str_ == 0) {
        oid_destroy(ptr);
        return 0;
    }
    int dots = char_count(str, '.');
    ptr->numbers_ = malloc(sizeof(int) * (dots + 1));
    if (ptr->numbers_ == 0) {
        oid_destroy(ptr);
        return 0;
    }
    ptr->length_ = dots + 1;
    const char* p = str;
    for (int i = 0; i <= dots && *p;) {
        char* eptr = 0;
        int num = strtol(p, &eptr, 10);
        if (*eptr != 0 && *eptr != '.') {
            // TODO: check for overflow/underflow
            oid_destroy(ptr);
            return 0;
        }
        ptr->numbers_[i++] = num;
        p = eptr;
        if (*p)
            ++p;
    }
    return ptr;
}

// compare two OIDs
int oid_compare(const void* p1, const void* p2) {
    const oid* o1 = *(oid* const*)p1;
    const oid* o2 = *(oid* const*)p2;
    int i1 = 0, i2 = 0;
    for (; i1 < o1->length_ && i2 < o2->length_; ++i1, ++i2) {
        if (o1->numbers_[i1] < o2->numbers_[i2])
            return -1;
        if (o1->numbers_[i1] > o2->numbers_[i2])
            return 1;
    }
    if (o1->length_ < o2->length_)
        return -1;
    if (o1->length_ > o2->length_)
        return 1;
    return 0;
}

int main() {
    const char* input[] = {
        "1.3.6.1.4.1.11.2.17.19.3.4.0.10",
        "1.3.6.1.4.1.11.2.17.5.2.0.79",
        "1.3.6.1.4.1.11.2.17.19.3.4.0.4",
        "1.3.6.1.4.1.11150.3.4.0.1",
        "1.3.6.1.4.1.11.2.17.19.3.4.0.1",
        "1.3.6.1.4.1.11150.3.4.0"
    };
    const int len = sizeof(input)/sizeof(input[0]);
    oid* oids[len];
    memset(oids, 0, sizeof(oids));
    int i;
    for (i = 0; i < len; ++i) {
        oids[i] = oid_create(input[i]);
        if (oids[i] == 0)
        {
            fprintf(stderr, "Out of memory\n");
            goto cleanup;
        }
    }
    qsort(oids, len, sizeof(oid*), oid_compare);
    for (i = 0; i < len; ++i)
        puts(oids[i]->str_);
cleanup:
    for (i = 0; i < len; ++i)
        oid_destroy(oids[i]);
    return 0;
}


var a : array of Integer := [5, 4, 3, 2, 1];
a.Sort; // ascending natural sort
PrintLn(a.Map(IntToStr).Join(','));  // 1,2,3,4,5


program SortExample

    function main()
        test1 int[] = [1,-1,8,-8,2,-2,7,-7,3,-3,6,-6,9,-9,4,-4,5,-5,0];
        test1.sort(sortFunction);

	for(i int from 1 to test1.getSize())
	    SysLib.writeStdout(test1[i]);
	end
    end

    function sortFunction(a any in, b any in) returns (int)
        return (a as int) - (b as int);
    end

end


using System;
using System.Linq;
using System.Collections.Generic;

public class Program
{
    public static void Main() {
        var oids = new [] {
            "1.3.6.1.4.1.11.2.17.19.3.4.0.10",
            "1.3.6.1.4.1.11.2.17.5.2.0.79",
            "1.3.6.1.4.1.11.2.17.19.3.4.0.4",
            "1.3.6.1.4.1.11150.3.4.0.1",
            "1.3.6.1.4.1.11.2.17.19.3.4.0.1",
            "1.3.6.1.4.1.11150.3.4.0"
        };

        var comparer = Comparer<string>.Create((a, b) => {
            int c = a.Split('.').Select(int.Parse)
	        .Zip(b.Split('.').Select(int.Parse),
                    (i, j) => i.CompareTo(j)).FirstOrDefault(x => x != 0);
            return c != 0 ? c : a.Length.CompareTo(b.Length);
        });

        Array.Sort(oids, comparer);

        Console.WriteLine(string.Join(Environment.NewLine, oids));
    }
}


#include <string>
#include <vector>
#include <algorithm>
#include <boost/tokenizer.hpp>
#include <iostream>

std::vector<std::string> splitOnChar ( std::string & s , const char c ) {
   typedef boost::tokenizer<boost::char_separator<char>> tokenizer ;
   std::vector<std::string> parts ;
   boost::char_separator<char> sep( &c ) ;
   tokenizer tokens( s , sep ) ;
   for ( auto it = tokens.begin( ) ; it != tokens.end( ) ; it++ )
      parts.push_back( *it ) ;
   return parts ;
}

bool myCompare ( const std::string & s1 , const std::string & s2 ) {
   std::string firstcopy( s1 ) ;
   std::string secondcopy ( s2 ) ;
   std::vector<std::string> firstparts( splitOnChar ( firstcopy, '.' ) ) ;
   std::vector<std::string> secondparts( splitOnChar ( secondcopy, '.' ) ) ;
   std::vector<int> numbers1( firstparts.size( ) ) ;
   std::vector<int> numbers2( secondparts.size( ) ) ;
   std::transform( firstparts.begin( ) , firstparts.end( ) , numbers1.begin( ) ,
	 []( std::string st ) { return std::stoi( st , nullptr ) ; } ) ;
   std::transform( secondparts.begin( ) , secondparts.end( ) , numbers2.begin( ) ,
	 []( std::string st ) { return std::stoi( st , nullptr ) ; } ) ;
   auto it1 = numbers1.begin( ) ;
   auto it2 = numbers2.begin( ) ;
   while ( *it1 == *it2 ) {
      it1++ ;
      it2++ ;
   }
   if ( it1 == numbers1.end( )  || it2 == numbers2.end( )  )
      return std::lexicographical_compare( s1.begin( ) , s1.end( ) , s2.begin( ) , s2.end( ) ) ;
   return *it1 < *it2 ;
}

int main( ) {
   std::vector<std::string> arrayOID { "1.3.6.1.4.1.11.2.17.19.3.4.0.10" ,
      "1.3.6.1.4.1.11.2.17.5.2.0.79" ,
      "1.3.6.1.4.1.11.2.17.19.3.4.0.4" ,
      "1.3.6.1.4.1.11150.3.4.0.1" ,
      "1.3.6.1.4.1.11.2.17.19.3.4.0.1" ,
      "1.3.6.1.4.1.11150.3.4.0" } ;
   std::sort( arrayOID.begin( ) , arrayOID.end( ) , myCompare ) ;
   for ( std::string s : arrayOID )
      std::cout << s << '\n' ;
   return 0 ;
}


import system'routines;
import extensions;

public program()
{
    var unsorted := new int[]{6, 2, 7, 8, 3, 1, 10, 5, 4, 9};

    console.printLine(unsorted.clone().sort(ifOrdered).asEnumerable())
}


list = [2, 4, 3, 1, 2]
IO.inspect Enum.sort(list)
IO.inspect Enum.sort(list, &(&1>&2))


List = [2, 4, 3, 1, 2].
SortedList = lists:sort(List).


(defn oid-vec [oid-str]
  (->> (clojure.string/split oid-str #"\.")
       (map #(Long. %))))

(defn oid-str [oid-vec]
  (clojure.string/join "." oid-vec))

;;
;; If vals differ before shorter vec ends,
;; use comparison of that "common header".
;; If common part matches, compare based on num elements.
;;
(defn oid-compare [a b]
  (let [min-len    (min (count a) (count b))
        common-cmp (compare (vec (take min-len a))
                            (vec (take min-len b)))]
    (if (zero? common-cmp)
      (compare (count a) (count b))
      common-cmp)))

(defn sort-oids [oid-strs]
  (->> (map  oid-vec oid-strs)
       (sort oid-compare)
       (map  oid-str)))


(defun oid->list (oid)
  (loop for start = 0 then (1+ pos)
        for pos = (position #\. oid :start start)
        collect (parse-integer oid :start start :end pos)
        while pos))

(defun list< (list1 list2)
  (loop for e1 in list1
        for e2 in list2
        do (cond ((< e1 e2)
                  (return t))
                 ((> e1 e2)
                  (return nil)))
        finally (return (< (length list1) (length list2)))))

(defun sort-oids (oids)
  (sort oids #'list< :key #'oid->list))

(defun main ()
  (let ((oids (list "1.3.6.1.4.1.11.2.17.19.3.4.0.10"
                    "1.3.6.1.4.1.11.2.17.5.2.0.79"
                    "1.3.6.1.4.1.11.2.17.19.3.4.0.4"
                    "1.3.6.1.4.1.11150.3.4.0.1"
                    "1.3.6.1.4.1.11.2.17.19.3.4.0.1"
                    "1.3.6.1.4.1.11150.3.4.0")))
    (dolist (oid (sort-oids oids))
      (write-line oid))))


// sorting an array in place
let nums = [| 2; 4; 3; 1; 2 |]
Array.sortInPlace nums

// create a sorted copy of a list
let nums2 = [2; 4; 3; 1; 2]
let sorted = List.sort nums2


create test-data 2 , 4 , 3 , 1 , 2 ,
test-data 5 cell-sort


package main

import (
    "fmt"
    "log"
    "math/big"
    "sort"
    "strings"
)

var testCases = []string{
    "1.3.6.1.4.1.11.2.17.19.3.4.0.10",
    "1.3.6.1.4.1.11.2.17.5.2.0.79",
    "1.3.6.1.4.1.11.2.17.19.3.4.0.4",
    "1.3.6.1.4.1.11150.3.4.0.1",
    "1.3.6.1.4.1.11.2.17.19.3.4.0.1",
    "1.3.6.1.4.1.11150.3.4.0",
}

// a parsed representation
type oid []big.Int

// "constructor" parses string representation
func newOid(s string) oid {
    ns := strings.Split(s, ".")
    os := make(oid, len(ns))
    for i, n := range ns {
        if _, ok := os[i].SetString(n, 10); !ok || os[i].Sign() < 0 {
            return nil
        }
    }
    return os
}

// "stringer" formats into string representation
func (o oid) String() string {
    s := make([]string, len(o))
    for i, n := range o {
        s[i] = n.String()
    }
    return strings.Join(s, ".")
}

func main() {
    // parse test cases
    os := make([]oid, len(testCases))
    for i, s := range testCases {
        os[i] = newOid(s)
        if os[i] == nil {
            log.Fatal("invalid OID")
        }
    }
    // sort
    sort.Slice(os, func(i, j int) bool {
        // "less" function must return true if os[i] < os[j]
        oi := os[i]
        for x, v := range os[j] {
            // lexicographic defintion: less if prefix or if element is <
            if x == len(oi) || oi[x].Cmp(&v) < 0 {
                return true
            }
            if oi[x].Cmp(&v) > 0 {
                break
            }
        }
        return false
    })
    // output sorted list
    for _, o := range os {
        fmt.Println(o)
    }
}


CALL [email protected](b, a, n)
! n = number of elements
! a = array to be sorted
! b = array of indices of a. b(1) 'points' to the minimum value etc.


' version 11-03-2016
' compile with: fbc -s console

#Include Once "crt/stdlib.bi"      ' needed for qsort subroutine

' Declare Sub qsort (ByVal As Any Ptr, <== point to start of array
'                    ByVal As size_t,  <== size of array
'                    ByVal As size_t,  <== size of array element
' ByVal As Function(ByVal As Any Ptr, ByVal As Any Ptr) As Long)  <== callback function
' declare callback function with Cdecl to ensures that the parameters are passed in the correct order
'
' size of long: 4 bytes on 32bit OS, 8 bytes on 64bit OS

' ascending
 Function callback Cdecl (ByVal element1 As Any Ptr, ByVal element2 As Any Ptr) As Long
     Function = *Cast(Long Ptr, element1) - *Cast(Long Ptr, element2)
End Function

' Function callback Cdecl (ByVal element1 As Any Ptr, ByVal element2 As Any Ptr) As Long
' Dim As Long e1 = *Cast(Long Ptr, element1)
' Dim As Long e2 = *Cast(Long Ptr, element2)
' Dim As Long result = Sgn(e1 - e2)
' If Sgn(e1) = -1 And Sgn(e2) = -1 Then result = -result
'     Function = result
' End Function

' ------=< MAIN >=------

Dim As Long i, array(20)

Dim As Long lb = LBound(array)
Dim As Long ub = UBound(array)

For i = lb To ub     ' fill array
    array(i) = 10 - i
Next

Print
Print "unsorted array"
For i = lb To ub     ' display array
    Print Using "###";array(i);
Next
Print : Print

' sort array
qsort(@array(lb), ub - lb +1, SizeOf(array), @callback)

Print "sorted array"
For i = lb To ub     ' show sorted array
    Print Using "###";array(i);
Next
Print

' empty keyboard buffer
While Inkey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End


import Data.List ( sort , intercalate )

splitString :: Eq a => (a) -> [a] -> [[a]]
splitString c [] = []
splitString c s = let ( item , rest ) = break ( == c ) s
                      ( _ , next ) = break ( /= c ) rest
		  in item : splitString c next

convertIntListToString :: [Int] -> String
convertIntListToString = intercalate "." . map show

orderOID :: [String] -> [String]
orderOID = map convertIntListToString . sort . map ( map read . splitString '.' )

oid :: [String]
oid = ["1.3.6.1.4.1.11.2.17.19.3.4.0.10" ,
    "1.3.6.1.4.1.11.2.17.5.2.0.79" ,
    "1.3.6.1.4.1.11.2.17.19.3.4.0.4" ,
    "1.3.6.1.4.1.11150.3.4.0.1" ,
    "1.3.6.1.4.1.11.2.17.19.3.4.0.1" ,
    "1.3.6.1.4.1.11150.3.4.0"]

main :: IO ( )
main = do
   mapM_ putStrLn $ orderOID oid


nums = [5, 2, 78, 2, 578, -42]
println( sort(nums) )           // sort in ascending order
println( nums.sortWith((>)) )   // sort in descending order


Public Sub Main()
Dim iArray As Integer[] = [8, 2, 5, 9, 1, 3, 6, 7, 4]
Dim iTemp As Integer
Dim sOutput As String

For Each iTemp In iArray.Sort()
  sOutput &= iTemp & ", "
Next

Print Left(sOutput, -2)

End


package com.rosettacode;

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

public class OIDListSorting {

    public static void main(String[] args) {

        final String dot = "\\.";

        final Comparator<String> oids_comparator = (o1, o2) -> {
            final String[] o1Numbers = o1.split(dot), o2Numbers = o2.split(dot);
            for (int i = 0; ; i++) {
                if (i == o1Numbers.length && i == o2Numbers.length)
                    return 0;
                if (i == o1Numbers.length)
                    return -1;
                if (i == o2Numbers.length)
                    return 1;
                final int nextO1Number = Integer.valueOf(o1Numbers[i]), nextO2Number = Integer.valueOf(o2Numbers[i]);
                final int result = Integer.compare(nextO1Number, nextO2Number);
                if (result != 0)
                    return result;
            }
        };

        Stream.of("1.3.6.1.4.1.11.2.17.19.3.4.0.10", "1.3.6.1.4.1.11.2.17.5.2.0.79", "1.3.6.1.4.1.11.2.17.19.3.4.0.4",
                  "1.3.6.1.4.1.11150.3.4.0.1", "1.3.6.1.4.1.11.2.17.19.3.4.0.1", "1.3.6.1.4.1.11150.3.4.0")
                .sorted(oids_comparator)
                .forEach(System.out::println);
    }
}


a := [ 8, 2, 5, 9, 1, 3, 6, 7, 4 ];
# Make a copy (with "b := a;", b and a would point to the same list)
b := ShallowCopy(a);

# Sort in place
Sort(a);
a;
# [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]

# Sort without changing the argument
SortedList(b);
# [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
b;
# [ 8, 2, 5, 9, 1, 3, 6, 7, 4 ]


package main
import "fmt"
import "sort"

func main() {
  nums := []int {2, 4, 3, 1, 2}
  sort.Ints(nums)
  fmt.Println(nums)
}


// version 1.0.6

class Oid(val id: String): Comparable<Oid> {
    override fun compareTo(other: Oid): Int {
        val splits1 = this.id.split('.')
        val splits2 = other.id.split('.')
        val minSize = if (splits1.size < splits2.size) splits1.size else splits2.size
        for (i in 0 until minSize) {
            if (splits1[i].toInt() < splits2[i].toInt()) return -1
            else if (splits1[i].toInt() > splits2[i].toInt()) return 1
        }
        return splits1.size.compareTo(splits2.size)
    }

    override fun toString() = id
}

fun main(args: Array<String>) {
    val oids = arrayOf(
        Oid("1.3.6.1.4.1.11.2.17.19.3.4.0.10"),
        Oid("1.3.6.1.4.1.11.2.17.5.2.0.79"),
        Oid("1.3.6.1.4.1.11.2.17.19.3.4.0.4"),
        Oid("1.3.6.1.4.1.11150.3.4.0.1"),
        Oid("1.3.6.1.4.1.11.2.17.19.3.4.0.1"),
        Oid("1.3.6.1.4.1.11150.3.4.0")
    )
    println(oids.sorted().joinToString("\n"))
}


local OIDs = {
    "1.3.6.1.4.1.11.2.17.19.3.4.0.10",
    "1.3.6.1.4.1.11.2.17.5.2.0.79",
    "1.3.6.1.4.1.11.2.17.19.3.4.0.4",
    "1.3.6.1.4.1.11150.3.4.0.1",
    "1.3.6.1.4.1.11.2.17.19.3.4.0.1",
    "1.3.6.1.4.1.11150.3.4.0"
}

function compare (a, b)
    local aList, bList, Na, Nb = {}, {}
    for num in a:gmatch("%d+") do table.insert(aList, num) end
    for num in b:gmatch("%d+") do table.insert(bList, num) end
    for i = 1, math.max(#aList, #bList) do
        Na, Nb = tonumber(aList[i]) or 0, tonumber(bList[i]) or 0
        if Na ~= Nb then return Na < Nb end
    end
end

table.sort(OIDs, compare)
for _, oid in pairs(OIDs) do print(oid) end


nums = [2,4,3,1,2] :: [Int]
sorted = List.sort nums


DIMENSION array(100)

   array = INT( RAN(100) )
   SORT(Vector=array, Sorted=array)


Module CheckIt {
      Flush ' empty stack of values
      Data "1.3.6.1.4.1.11.2.17.19.3.4.0.4" ,  "1.3.6.1.4.1.11.2.17.19.3.4.0.1",  "1.3.6.1.4.1.11150.3.4.0.1"
      Data "1.3.6.1.4.1.11.2.17.19.3.4.0.10", "1.3.6.1.4.1.11.2.17.5.2.0.79",  "1.3.6.1.4.1.11150.3.4.0"
      \\ Inventories of type queue can get same keys, and have sort where numbers (float type) as part of key count as numbers
      Inventory queue OID
      \\ prepare keys (replace dot to #)
      While not empty {
            Append OID, Replace$(".","#", letter$)
      }
      Sort Ascending OID
      n=Each(OID)
      a$=""
      While n {
            \\ replace # to dot
            a$+=Replace$("#",".", Eval$(n))+{
            }
      }
      Clipboard a$
      Report a$
}
Checkit