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 BubbleSort(INT ARRAY a INT size)
  INT count,changed,i,tmp

  count=size
  IF count<=1 THEN RETURN FI

  DO
    changed=0
    count==-1
    FOR i=0 TO count-1
    DO
      IF a(i)>a(i+1) THEN
        tmp=a(i) a(i)=a(i+1) a(i+1)=tmp
        changed=1
      FI
    OD
  UNTIL changed=0
  OD
RETURN

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

PROC Main()
  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]

  Test(a,10)
  Test(b,21)
  Test(c,8)
  Test(d,12)
RETURN


public function bubbleSort(toSort:Array):Array
{
	var changed:Boolean = false;

	while (!changed)
	{
		changed = true;

		for (var i:int = 0; i < toSort.length - 1; i++)
		{
			if (toSort[i] > toSort[i + 1])
			{
				var tmp:int = toSort[i];
				toSort[i] = toSort[i + 1];
				toSort[i + 1] = tmp;

				changed = false;
			}
		}
	}

	return toSort;
}


generic
 type Element is private;
 with function "=" (E1, E2 : Element) return Boolean is <>;
 with function "<" (E1, E2 : Element) return Boolean is <>;
 type Index is (<>);
 type Arr is array (Index range <>) of Element;
procedure Bubble_Sort (A : in out Arr);

procedure Bubble_Sort (A : in out Arr) is
 Finished : Boolean;
 Temp     : Element;
begin
 loop
  Finished := True;
  for J in A'First .. Index'Pred (A'Last) loop
   if A (Index'Succ (J)) < A (J) then
    Finished := False;
    Temp := A (Index'Succ (J));
    A (Index'Succ (J)) := A (J);
    A (J) := Temp;
   end if;
  end loop;
  exit when Finished;
 end loop;
end Bubble_Sort;

--  Example of usage:
with Ada.Text_IO; use Ada.Text_IO;
with Bubble_Sort;
procedure Main is
 type Arr is array (Positive range <>) of Integer;
 procedure Sort is new
  Bubble_Sort
   (Element => Integer,
    Index   => Positive,
    Arr     => Arr);
 A : Arr := (1, 3, 256, 0, 3, 4, -1);
begin
 Sort (A);
 for J in A'Range loop
  Put (Integer'Image (A (J)));
 end loop;
 New_Line;
end Main;


begin
    comment Sorting algorithms/Bubble sort - Algol 60;
    integer nA;
    nA:=20;

    begin
        integer array A[1:20];

        procedure bubblesort(lb,ub);
        value lb,ub; integer lb,ub;
        begin
            integer i;
            boolean swapped;
            swapped :=true;
            for i:=1 while swapped do begin
                swapped:=false;
                for i:=lb step  1 until ub-1 do if A[i]>A[i+1] then begin
                    integer temp;
                    temp  :=A[i];
                    A[i]  :=A[i+1];
                    A[i+1]:=temp;
                    swapped:=true
                end
            end
        end bubblesort;

        procedure inittable(lb,ub);
        value lb,ub; integer lb,ub;
        begin
            integer i;
            for i:=lb step 1 until ub do A[i]:=entier(rand*100)
        end inittable;

        procedure writetable(lb,ub);
        value lb,ub; integer lb,ub;
        begin
            integer i;
            for i:=lb step 1 until ub do outinteger(1,A[i]);
            outstring(1,"\n")
        end writetable;

        inittable(1,nA);
        writetable(1,nA);
        bubblesort(1,nA);
        writetable(1,nA)
    end
end


MODE DATA = INT;
PROC swap = (REF[]DATA slice)VOID:
(
  DATA tmp = slice[1];
  slice[1] := slice[2];
  slice[2] := tmp
);

PROC sort = (REF[]DATA array)VOID:
(
  BOOL sorted;
  INT shrinkage := 0;
  FOR size FROM UPB array - 1 BY -1 WHILE
    sorted := TRUE;
    shrinkage +:= 1;
    FOR i FROM LWB array TO size DO
      IF array[i+1] < array[i] THEN
        swap(array[i:i+1]);
        sorted := FALSE
      FI
    OD;
    NOT sorted
  DO SKIP OD
);

main:(
  [10]INT random := (1,6,3,5,2,9,8,4,7,0);

  printf(($"Before: "10(g(3))l$,random));
  sort(random);
  printf(($"After: "10(g(3))l$,random))
)


begin
    % As algol W does not allow overloading, we have to have type-specific   %
    % sorting procedures - this bubble sorts an integer array                %
    % as there is no way for the procedure to determine the array bounds, we %
    % pass the lower and upper bounds in lb and ub                           %
    procedure bubbleSortIntegers( integer array item( * )
                                ; integer value lb
                                ; integer value ub
                                ) ;
    begin
        integer lower, upper;

        lower := lb;
        upper := ub;

        while
            begin
                logical swapped;
                upper   := upper - 1;
                swapped := false;
                for i := lower until upper
                do begin
                    if item( i ) > item( i + 1 )
                    then begin
                        integer val;
                        val           := item( i );
                        item( i )     := item( i + 1 );
                        item( i + 1 ) := val;
                        swapped       := true;
                    end if_must_swap ;
                end for_i ;
                swapped
            end
        do  begin end;
    end bubbleSortIntegers ;

    begin % test the bubble sort                                             %
        integer array data( 1 :: 10 );

        procedure writeData ;
        begin
            write( data( 1 ) );
            for i := 2 until 10 do writeon( data( i ) );
        end writeData ;

        % initialise data to unsorted values                                 %
        integer       dPos;
        dPos  := 1;
        for i := 16, 2, -6, 9, 90, 14, 0, 23, 8, 9
        do begin
            data( dPos ) := i;
            dPos         := dPos + 1;
        end for_i ;

        i_w := 3; s_w := 1; % set output format %
        writeData;
        bubbleSortIntegers( data, 1, 10 );
        writeData;
    end test
end.


-- In-place bubble sort.
on bubbleSort(theList, l, r) -- Sort items l thru r of theList.
    set listLen to (count theList)
    if (listLen < 2) then return
    -- Convert negative and/or transposed range indices.
    if (l < 0) then set l to listLen + l + 1
    if (r < 0) then set r to listLen + r + 1
    if (l > r) then set {l, r} to {r, l}

    -- The list as a script property to allow faster references to its items.
    script o
        property lst : theList
    end script

    set lPlus1 to l + 1
    repeat with j from r to lPlus1 by -1
        set lv to o's lst's item l
        -- Hereafter lv is only set when necessary and from rv rather than from the list.
        repeat with i from lPlus1 to j
            set rv to o's lst's item i
            if (lv > rv) then
                set o's lst's item (i - 1) to rv
                set o's lst's item i to lv
            else
                set lv to rv
            end if
        end repeat
    end repeat

    return -- nothing.
end bubbleSort
property sort : bubbleSort

-- Demo:
local aList
set aList to {61, 23, 11, 55, 1, 94, 71, 98, 70, 33, 29, 77, 58, 95, 2, 52, 68, 29, 27, 37, 74, 38, 45, 73, 10}
sort(aList, 1, -1) -- Sort items 1 thru -1 of aList.
return aList


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

 /* 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 bubbleSort
    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
/******************************************************************/
/*         bubble sort                                              */
/******************************************************************/
/* r0 contains the address of table */
/* r1 contains the first element    */
/* r2 contains the number of element */
bubbleSort:
    push {r1-r9,lr}           @ save registers
    sub r2,r2,#1              @ compute i = n - 1
    add r8,r1,#1
1:                            @ start loop 1
    mov r3,r1                 @ start index
    mov r9,#0
    sub r7,r2,#1
2:                            @ start loop 2
    add r4,r3,#1
    ldr r5,[r0,r3,lsl #2]     @ load value A[j]
    ldr r6,[r0,r4,lsl #2]     @ load value A[j+1]
    cmp r6,r5                 @ compare value
    strlt r6,[r0,r3,lsl #2]   @ if smaller inversion
    strlt r5,[r0,r4,lsl #2]
    movlt r9,#1               @ top table not sorted
    add r3,#1                 @ increment index j
    cmp r3,r7                 @ end ?
    ble 2b                    @ no -> loop 2
    cmp r9,#0                 @ table sorted ?
    beq 100f                  @ yes -> end

    sub r2,r2,#1              @ decrement i
    cmp r2,r8                 @ end ?
    bge 1b                    @ no -> loop 1

100:
    pop {r1-r9,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"


bubbleSort: function [items][
    len: size items
    loop len [j][
        i: 1
        while [i =< len-j] [
            if items\[i] < items\[i-1] [
                tmp: items\[i]
                items\[i]: items\[i-1]
                items\[i-1]: tmp
            ]
            i: i + 1
        ]
    ]
    items
]

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


var =
(
dog
cat
pile
abc
)
MsgBox % bubblesort(var)

bubblesort(var) ; each line of var is an element of the array
{
  StringSplit, array, var, `n
  hasChanged = 1
  size := array0
  While hasChanged
  {
    hasChanged = 0
    Loop, % (size - 1)
    {
      i := array%A_Index%
      aj := A_Index + 1
      j := array%aj%
      If (j < i)
      {
        temp := array%A_Index%
        array%A_Index% := array%aj%
        array%aj% := temp
        hasChanged = 1
      }
    }
  }
  Loop, % size
    sorted .= array%A_Index% . "`n"
  Return sorted
}


{ # read every line into an array
  line[NR] = $0
}
END { # sort it with bubble sort
  do {
    haschanged = 0
    for(i=1; i < NR; i++) {
      if ( line[i] > line[i+1] ) {
	t = line[i]
	line[i] = line[i+1]
	line[i+1] = t
	haschanged = 1
      }
    }
  } while ( haschanged == 1 )
  # print it
  for(i=1; i <= NR; i++) {
    print line[i]
  }
}


DO
  changed = 0
  FOR I = 1 TO size -1
    IF nums(I) > nums(I + 1) THEN
      tmp = nums(I)
      nums(I) = nums(I + 1)
      nums(I + 1) = tmp
      changed = 1
    END IF
  NEXT
LOOP WHILE(NOT changed)


get "libhdr"

let bubblesort(v, length) be
$(  let sorted = false
    until sorted
    $(  sorted := true
        length := length - 1
        for i=0 to length-1
            if v!i > v!(i+1)
            $(  let x = v!i
                v!i := v!(i+1)
                v!(i+1) := x
                sorted := false
            $)
    $)
$)

let start() be
$(  let v = table 10,8,6,4,2,1,3,5,7,9
    bubblesort(v, 10)
    for i=0 to 9 do writef("%N ", v!i)
    wrch('*N')
$)


using System;
using System.Collections.Generic;

namespace RosettaCode.BubbleSort
{
    public static class BubbleSortMethods
    {
        //The "this" keyword before the method parameter identifies this as a C# extension
        //method, which can be called using instance method syntax on any generic list,
        //without having to modify the generic List<T> code provided by the .NET framework.
        public static void BubbleSort<T>(this List<T> list) where T : IComparable
        {
            bool madeChanges;
            int itemCount = list.Count;
            do
            {
                madeChanges = false;
                itemCount--;
                for (int i = 0; i < itemCount; i++)
                {
                    if (list[i].CompareTo(list[i + 1]) > 0)
                    {
                        T temp = list[i + 1];
                        list[i + 1] = list[i];
                        list[i] = temp;
                        madeChanges = true;
                    }
                }
            } while (madeChanges);
        }
    }

    //A short test program to demonstrate the BubbleSort. The compiler will change the
    //call to testList.BubbleSort() into one to BubbleSortMethods.BubbleSort<T>(testList).
    class Program
    {
        static void Main()
        {
            List<int> testList = new List<int> { 3, 7, 3, 2, 1, -4, 10, 12, 4 };
            testList.BubbleSort();
            foreach (var t in testList) Console.Write(t + " ");
        }
    }
}


(ns bubblesort
  (:import java.util.ArrayList))

(defn bubble-sort
  "Sort in-place.
  arr must implement the Java List interface and should support
  random access, e.g. an ArrayList."
  ([arr] (bubble-sort compare arr))
  ([cmp arr]
     (letfn [(swap! [i j]
                    (let [t (.get arr i)]
                      (doto arr
                        (.set i (.get arr j))
                        (.set j t))))
             (sorter [stop-i]
                     (let [changed (atom false)]
                       (doseq [i (range stop-i)]
                         (if (pos? (cmp (.get arr i) (.get arr (inc i))))
                           (do
                             (swap! i (inc i))
                             (reset! changed true))))
                       @changed))]
       (doseq [stop-i (range (dec (.size arr)) -1 -1)
               :while (sorter stop-i)])
       arr)))

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


% Bubble-sort an array in place.
bubble_sort = proc [T: type] (a: array[T])
              where T has lt: proctype (T,T) returns (bool)

    bound_lo: int := array[T]$low(a)
    bound_hi: int := array[T]$high(a)

    for hi: int in int$from_to_by(bound_hi, bound_lo, -1) do
        for i: int in int$from_to(bound_lo, hi-1) do
            if a[hi] < a[i] then
                temp: T := a[i]
                a[i] := a[hi]
                a[hi] := temp
            end
        end
    end
end bubble_sort

% Print an array
print_arr = proc [T: type] (a: array[T], w: int, s: stream)
            where T has unparse: proctype (T) returns (string)
    for el: T in array[T]$elements(a) do
        stream$putright(s, T$unparse(el), w)
    end
    stream$putc(s, '\n')
end print_arr

start_up = proc ()
    ai = array[int]
    po: stream := stream$primary_output()
    test: ai := ai$[7, -5, 0, 2, 99, 16, 4, 20, 47, 19]

    stream$puts(po, "Before: ") print_arr[int](test, 3, po)
    bubble_sort[int](test)
    stream$puts(po, "After:  ") print_arr[int](test, 3, po)
end start_up


# bubble_sort(var [value1 value2...]) sorts a list of integers.
function(bubble_sort var)
  math(EXPR last "${ARGC} - 1")  # Prepare to sort ARGV[1]..ARGV[last].
  set(again YES)
  while(again)
    set(again NO)
    math(EXPR last "${last} - 1")               # Decrement last index.
    foreach(index RANGE 1 ${last})              # Loop for each index.
      math(EXPR index_plus_1 "${index} + 1")
      set(a "${ARGV${index}}")                  # a = ARGV[index]
      set(b "${ARGV${index_plus_1}}")           # b = ARGV[index + 1]
      if(a GREATER "${b}")                      # If a > b...
        set(ARGV${index} "${b}")                # ...then swap a, b
        set(ARGV${index_plus_1} "${a}")         #    inside ARGV.
        set(again YES)
      endif()
    endforeach(index)
  endwhile()

  set(answer)
  math(EXPR last "${ARGC} - 1")
  foreach(index RANGE 1 "${last}")
    list(APPEND answer "${ARGV${index}}")
  endforeach(index)
  set("${var}" "${answer}" PARENT_SCOPE)
endfunction(bubble_sort)


       IDENTIFICATION DIVISION.
       PROGRAM-ID.                      BUBBLESORT.
       AUTHOR.                          DAVE STRATFORD.
       DATE-WRITTEN.                    MARCH 2010.
       INSTALLATION.                    HEXAGON SYSTEMS LIMITED.

       ENVIRONMENT DIVISION.
       CONFIGURATION SECTION.
       SOURCE-COMPUTER.                 ICL VME.
       OBJECT-COMPUTER.                 ICL VME.

       INPUT-OUTPUT SECTION.
       FILE-CONTROL.
           SELECT FA-INPUT-FILE  ASSIGN FL01.
           SELECT FB-OUTPUT-FILE ASSIGN FL02.

       DATA DIVISION.
       FILE SECTION.

       FD  FA-INPUT-FILE.
       01  FA-INPUT-REC.
         03  FA-DATA                    PIC S9(6).

       FD  FB-OUTPUT-FILE.
       01  FB-OUTPUT-REC                PIC S9(6).

       WORKING-STORAGE SECTION.
       01  WA-IDENTITY.
         03  WA-PROGNAME                PIC X(10) VALUE "BUBBLESORT".
         03  WA-VERSION                 PIC X(6) VALUE "000001".

       01  WB-TABLE.
         03  WB-ENTRY                   PIC 9(8) COMP SYNC OCCURS 100000
                                                  INDEXED BY WB-IX-1.

       01  WC-VARS.
         03  WC-SIZE                    PIC S9(8) COMP SYNC.
         03  WC-TEMP                    PIC S9(8) COMP SYNC.
         03  WC-END                     PIC S9(8) COMP SYNC.
         03  WC-LAST-CHANGE             PIC S9(8) COMP SYNC.

       01  WF-CONDITION-FLAGS.
         03  WF-EOF-FLAG                PIC X.
           88  END-OF-FILE              VALUE "Y".
         03  WF-EMPTY-FILE-FLAG         PIC X.
           88  EMPTY-FILE               VALUE "Y".

       PROCEDURE DIVISION.
       A-MAIN SECTION.
       A-000.
           PERFORM B-INITIALISE.
           IF NOT EMPTY-FILE
              PERFORM C-SORT.
           PERFORM D-FINISH.

       A-999.
           STOP RUN.

       B-INITIALISE SECTION.
       B-000.
           DISPLAY "*** " WA-PROGNAME " VERSION "
                          WA-VERSION " STARTING ***".

           MOVE ALL "N" TO WF-CONDITION-FLAGS.
           OPEN INPUT FA-INPUT-FILE.
           SET WB-IX-1 TO 0.

           READ FA-INPUT-FILE AT END MOVE "Y" TO WF-EOF-FLAG
                                                 WF-EMPTY-FILE-FLAG.

           PERFORM BA-READ-INPUT UNTIL END-OF-FILE.

           CLOSE FA-INPUT-FILE.

           SET WC-SIZE TO WB-IX-1.

       B-999.
           EXIT.

       BA-READ-INPUT SECTION.
       BA-000.
           SET WB-IX-1 UP BY 1.
           MOVE FA-DATA TO WB-ENTRY(WB-IX-1).

           READ FA-INPUT-FILE AT END MOVE "Y" TO WF-EOF-FLAG.

       BA-999.
           EXIT.

       C-SORT SECTION.
       C-000.
           DISPLAY "SORT STARTING".

           MOVE WC-SIZE TO WC-END.
           PERFORM E-BUBBLE UNTIL WC-END = 1.

           DISPLAY "SORT FINISHED".

       C-999.
           EXIT.

       D-FINISH SECTION.
       D-000.
           OPEN OUTPUT FB-OUTPUT-FILE.
           SET WB-IX-1 TO 1.

           PERFORM DA-WRITE-OUTPUT UNTIL WB-IX-1 > WC-SIZE.

           CLOSE FB-OUTPUT-FILE.

           DISPLAY "*** " WA-PROGNAME " FINISHED ***".

       D-999.
           EXIT.

       DA-WRITE-OUTPUT SECTION.
       DA-000.
           WRITE FB-OUTPUT-REC FROM WB-ENTRY(WB-IX-1).
           SET WB-IX-1 UP BY 1.

       DA-999.
           EXIT.

       E-BUBBLE SECTION.
       E-000.
           MOVE 1 TO WC-LAST-CHANGE.

           PERFORM F-PASS VARYING WB-IX-1 FROM 1 BY 1
                          UNTIL WB-IX-1 = WC-END.

           MOVE WC-LAST-CHANGE TO WC-END.

       E-999.
           EXIT.

       F-PASS SECTION.
       F-000.
           IF WB-ENTRY(WB-IX-1) > WB-ENTRY(WB-IX-1 + 1)
              SET  WC-LAST-CHANGE        TO WB-IX-1
              MOVE WB-ENTRY(WB-IX-1)     TO WC-TEMP
              MOVE WB-ENTRY(WB-IX-1 + 1) TO WB-ENTRY(WB-IX-1)
              MOVE WC-TEMP               TO WB-ENTRY(WB-IX-1 + 1).

       F-999.
           EXIT.


(defun bubble-sort (sequence &optional (compare #'<))
  "sort a sequence (array or list) with an optional comparison function (cl:< is the default)"
  (loop with sorted = nil until sorted do
        (setf sorted t)
        (loop for a below (1- (length sequence)) do
              (unless (funcall compare (elt sequence a)
                                       (elt sequence (1+ a)))
                (rotatef (elt sequence a)
                         (elt sequence (1+ a)))
                (setf sorted nil)))))


include "cowgol.coh";

# Comparator interface, on the model of C, i.e:
# foo < bar => -1, foo == bar => 0, foo > bar => 1
typedef CompRslt is int(-1, 1);
interface Comparator(foo: intptr, bar: intptr): (rslt: CompRslt);

# Bubble sort an array of pointer-sized integers given a comparator function
# (This is the closest you can get to polymorphism in Cowgol).
sub bubbleSort(A: [intptr], len: intptr, comp: Comparator) is
    loop
        var swapped: uint8 := 0;
        var i: intptr := 1;
        var a := @next A;
        while i < len loop
            if comp([@prev a], [a]) == 1 then
                var t := [a];
                [a] := [@prev a];
                [@prev a] := t;
                swapped := 1;
            end if;
            a := @next a;
            i := i + 1;
        end loop;
        if swapped == 0 then
            return;
        end if;
    end loop;
end sub;

# Test: sort a list of numbers
sub NumComp implements Comparator is
    # Compare the inputs as numbers
    if foo < bar then rslt := -1;
    elseif foo > bar then rslt := 1;
    else rslt := 0;
    end if;
end sub;

# Numbers
var numbers: intptr[] := {
    65,13,4,84,29,5,96,73,5,11,17,76,38,26,44,20,36,12,44,51,79,8,99,7,19,95,26
};

# Sort the numbers in place
bubbleSort(&numbers as [intptr], @sizeof numbers, NumComp);

# Print the numbers (hopefully in order)
var i: @indexof numbers := 0;
while i < @sizeof numbers loop
    print_i32(numbers[i] as uint32);
    print_char(' ');
    i := i + 1;
end loop;
print_nl();


import std.stdio, std.algorithm : swap;

T[] bubbleSort(T)(T[] data) pure nothrow
{
    foreach_reverse (n; 0 .. data.length)
    {
        bool swapped;
        foreach (i; 0 .. n)
            if (data[i] > data[i + 1]) {
                swap(data[i], data[i + 1]);
                swapped = true;
            }
        if (!swapped)
            break;
    }
    return data;
}

void main()
{
    auto array = [28, 44, 46, 24, 19, 2, 17, 11, 25, 4];
    writeln(array.bubbleSort());
}


List<num> bubbleSort(List<num> list) {
  var retList = new List<num>.from(list);
  var tmp;
  var swapped = false;
  do {
    swapped = false;
    for(var i = 1; i < retList.length; i++) {
      if(retList[i - 1] > retList[i]) {
        tmp = retList[i - 1];
        retList[i - 1] = retList[i];
        retList[i] = tmp;
        swapped = true;
      }
    }
  } while(swapped);

  return retList;
}


F sort_disjoint_sublist(&data, indices)
   V sindices = sorted(indices)
   V values = sorted(sindices.map(i -> @data[i]))
   L(index, value) zip(sindices, values)
      data[index] = value

V d = [7, 6, 5, 4, 3, 2, 1, 0]
V i = [6, 1, 7]
sort_disjoint_sublist(&d, i)
print(d)


program TestBubbleSort;

{$APPTYPE CONSOLE}

{.$DEFINE DYNARRAY}  // remove '.' to compile with dynamic array

type
  TItem = Integer;   // declare ordinal type for array item
{$IFDEF DYNARRAY}
  TArray = array of TItem;          // dynamic array
{$ELSE}
  TArray = array[0..15] of TItem;   // static array
{$ENDIF}

procedure BubbleSort(var A: TArray);
var
  Item: TItem;
  K, L, J: Integer;

begin
  L:= Low(A) + 1;
  repeat
    K:= High(A);
    for J:= High(A) downto L do begin
      if A[J - 1] > A[J] then begin
        Item:= A[J - 1];
        A[J - 1]:= A[J];
        A[J]:= Item;
        K:= J;
      end;
    end;
    L:= K + 1;
  until L > High(A);
end;

var
  A: TArray;
  I: Integer;

begin
{$IFDEF DYNARRAY}
  SetLength(A, 16);
{$ENDIF}
  for I:= Low(A) to High(A) do
    A[I]:= Random(100);
  for I:= Low(A) to High(A) do
    Write(A[I]:3);
  Writeln;
  BubbleSort(A);
  for I:= Low(A) to High(A) do
    Write(A[I]:3);
  Writeln;
  Readln;
end.


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

BYTE FUNC InSet(INT ARRAY s INT size INT v)
  INT i

  FOR i=0 TO size-1
  DO
    IF s(i)=v THEN
      RETURN (1)
    FI
  OD
RETURN (0)

PROC Sort(INT ARRAY arr INT arrSize
          INT ARRAY ind INT indSize)
  INT i,j,minpos,tmp

  FOR i=0 TO arrSize-2
  DO
    IF InSet(ind,indSize,i) THEN
      minpos=i
      FOR j=i+1 TO arrSize-1
      DO
        IF InSet(ind,indSize,j)=1 AND arr(minpos)>arr(j) THEN
          minpos=j
        FI
      OD

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

PROC Test(INT ARRAY arr INT arrSize
          INT ARRAY ind INT indSize)
  PrintE("Array before sort:")
  PrintArray(arr,arrSize)
  PrintE("Indices:")
  PrintArray(ind,indSize)
  Sort(arr,arrSize,ind,indSize)
  PrintE("Array after sort:")
  PrintArray(arr,arrSize)
RETURN

PROC Main()
  INT ARRAY
    arr(8)=[7 6 5 4 3 2 1 0],
    ind(3)=[6 1 7]

  Test(arr,8,ind,3)
RETURN


with Ada.Text_IO, GNAT.Bubble_Sort;
use  Ada.Text_IO;

procedure DisjointSort is

   package Int_Io is new Integer_IO (Integer);

   subtype Index_Range is Natural range 1 .. 8;
   Input_Array : array (Index_Range) of Integer := (7, 6, 5, 4, 3, 2, 1, 0);

   subtype Subindex_Range is Natural range 1 .. 3;
   type Sub_Arrays is array (Subindex_Range) of Integer;

   Sub_Index : Sub_Arrays := (7, 2, 8);
   Sub_Array : Sub_Arrays;

   -- reuse of the somehow generic GNAT.Bubble_Sort (for Ada05)

   procedure Sort (Work_Array : in out Sub_Arrays) is
      procedure Exchange (Op1, Op2 : Natural) is
         Temp : Integer;
      begin
         Temp             := Work_Array (Op1);
         Work_Array (Op1) := Work_Array (Op2);
         Work_Array (Op2) := Temp;
      end Exchange;

      function Lt (Op1, Op2 : Natural) return Boolean is
      begin
         return (Work_Array (Op1) < Work_Array (Op2));
      end Lt;
   begin
      GNAT.Bubble_Sort.Sort
        (N    => Subindex_Range'Last,
         Xchg => Exchange'Unrestricted_Access,
         Lt   => Lt'Unrestricted_Access);
   end Sort;

begin
   -- as the positions are not ordered, first sort the positions
   Sort (Sub_Index);
   -- extract the values to be sorted
   for I in Subindex_Range loop
      Sub_Array (I) := Input_Array (Sub_Index (I));
   end loop;
   Sort (Sub_Array);
   -- put the sorted values at the right place
   for I in Subindex_Range loop
      Input_Array (Sub_Index (I))  := Sub_Array (I);
   end loop;

   for I in Index_Range loop
      Int_Io.Put (Input_Array (I), Width => 2);
   end loop;
   New_Line;

end DisjointSort;


/* Bubble sort an array of integers */
proc nonrec bubblesort([*] int a) void:
    bool sorted;
    int i, temp;
    sorted := false;
    while not sorted do
        sorted := true;
        for i from 1 upto dim(a,1)-1 do
            if a[i-1] > a[i] then
                sorted := false;
                temp := a[i-1];
                a[i-1] := a[i];
                a[i] := temp
            fi
        od
    od
corp

/* Test */
proc nonrec main() void:
    int i;
    [10] int a = (9, -5, 3, 3, 24, -16, 3, -120, 250, 17);

    write("Before sorting: ");
    for i from 0 upto 9 do write(a[i]:5) od;
    writeln();

    bubblesort(a);
    write("After sorting:  ");
    for i from 0 upto 9 do write(a[i]:5) od
corp


func bubbleSort(list) {
    var done = false
    while !done {
        done = true
        for i in 1..(list.Length()-1) {
            if list[i - 1] > list[i] {
                var x = list[i]
                list[i] = list[i - 1]
                list[i - 1] = x
                done = false
            }
        }
    }
}

var xs = [3,1,5,4,2,6]
bubbleSort(xs)
print(xs)


begin % sort a disjoint sub-set of a list                         %
    % Quicksorts in-place the array of integers v, from lb to ub %
    procedure quicksort ( integer array v( * )
                        ; integer value lb, ub
                        ) ;
    if ub > lb then begin
        % more than one element, so must sort %
        integer left, right, pivot;
        left   := lb;
        right  := ub;
        % choosing the middle element of the array as the pivot %
        pivot  := v( left + ( ( right + 1 ) - left ) div 2 );
        while begin
            while left  <= ub and v( left  ) < pivot do left  := left  + 1;
            while right >= lb and v( right ) > pivot do right := right - 1;
            left <= right
        end do begin
            integer swap;
            swap       := v( left  );
            v( left  ) := v( right );
            v( right ) := swap;
            left       := left  + 1;
            right      := right - 1
        end while_left_le_right ;
        quicksort( v, lb,   right );
        quicksort( v, left, ub    )
    end quicksort ;
    % Quicksorts in-place the array of integers v, using          %
    % the indxexes in unsortedIndexes which has bounds lb to ub   %
    % it is assumed all elements of unsortedIndexes are in the    %
    % range for subscripts of v                                   %
    procedure indexedQuicksort ( integer array v, unsortedIndexes ( * )
                               ; integer value lb, ub
                               ) ;
    if ub > lb then begin
        % more than one element, so must sort %
        integer array indexes ( lb :: ub );
        integer left, right, pivot, p;
        % sort the indexes %
        for i := lb until ub do indexes( i ) := unsortedIndexes( i );
        quicksort( indexes, lb, ub );
        % sort the indexed items of the v array %
        left   := lb;
        right  := ub;
        % choosing the middle element of the array as the pivot %
        p      := left + ( ( ( right + 1 ) - left ) div 2 );
        pivot  := v( indexes( p ) );
        while begin
            while left  <= ub and v( indexes( left  ) ) < pivot do left  := left  + 1;
            while right >= lb and v( indexes( right ) ) > pivot do right := right - 1;
            left <= right
        end do begin
            integer swap;
            swap                  := v( indexes( left  ) );
            v( indexes( left  ) ) := v( indexes( right ) );
            v( indexes( right ) ) := swap;
            left                  := left  + 1;
            right                 := right - 1
        end while_left_le_right ;
        indexedQuicksort( v, indexes, lb,   right );
        indexedQuicksort( v, indexes, left, ub    )
    end indexedQuicksort ;
    begin % task %
        integer array indexes ( 0 :: 2 );
        integer array values  ( 0 :: 7 );
        integer aPos;
        aPos := 0;
        for v := 7, 6, 5, 4, 3, 2, 1, 0 do begin
            values( aPos ) := v;
            aPos           := aPos + 1
        end for_v ;
        indexes( 0 ) := 6;
        indexes( 1 ) := 1;
        indexes( 2 ) := 7;
        i_w := 1; s_w := 0; % set output formatting %
        write( "[" );
        for v := 0 until 7 do writeon( " ", values( v ) );
        writeon( " ]" );
        indexedQuicksort( values, indexes, 0, 2 );
        writeon( " -> [" );
        for v := 0 until 7 do writeon( " ", values( v ) );
        writeon( " ]" )
    end
end.


      ∇SDS[⎕]∇
    ∇
[0]   Z←I SDS L
[1]   L[I[⍋I]]←Z[⍋Z←L[I←∪I]]
[2]   Z←L
    ∇


use AppleScript version "2.4"
use framework "Foundation"
use scripting additions

-- disjointSort :: [Int] -> [Int] -> [Int]
on disjointSort(ixs, xs)
    set ks to sort(ixs)
    script nth -- 1-based index
        on |λ|(k)
            item (succ(k)) of xs
        end |λ|
    end script
    set dct to mapFromList(zip(ks, sort(map(nth, ks))))

    script build
        on |λ|(x, i)
            set mb to lookupDict(pred(i) as string, dct)
            if Nothing of mb then
                x
            else
                |Just| of mb
            end if
        end |λ|
    end script
    map(build, xs)
end disjointSort

on run
    disjointSort({6, 1, 7}, {7, 6, 5, 4, 3, 2, 1, 0})
end run

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

-- Just :: a -> Maybe a
on Just(x)
    {type:"Maybe", Nothing:false, Just:x}
end Just

-- Nothing :: Maybe a
on Nothing()
    {type:"Maybe", Nothing:true}
end Nothing

-- length :: [a] -> Int
on |length|(xs)
    set c to class of xs
    if list is c or string is c then
        length of xs
    else
        (2 ^ 29 - 1) -- (maxInt - simple proxy for non-finite)
    end if
end |length|

-- lookupDict :: a -> Dict -> Maybe b
on lookupDict(k, dct)
    set ca to current application
    set v to (ca's NSDictionary's dictionaryWithDictionary:dct)'s objectForKey:k
    if v ≠ missing value then
        Just(item 1 of ((ca's NSArray's arrayWithObject:v) as list))
    else
        Nothing()
    end if
end lookupDict

-- 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

-- mapFromList :: [(k, v)] -> Dict
on mapFromList(kvs)
    set tpl to unzip(kvs)
    script
        on |λ|(x)
            x as string
        end |λ|
    end script
    (current application's NSDictionary's ¬
        dictionaryWithObjects:(|2| of tpl) ¬
            forKeys:map(result, |1| of tpl)) as record
end mapFromList

-- min :: Ord a => a -> a -> a
on min(x, y)
    if y < x then
        y
    else
        x
    end if
end min

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

-- pred :: Enum a => a -> a
on pred(x)
    x - 1
end pred

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

-- succ :: Enum a => a -> a
on succ(x)
    1 + x
end succ

-- take :: Int -> [a] -> [a]
-- take :: Int -> String -> String
on take(n, xs)
    set c to class of xs
    if list is c then
        if 0 < n then
            items 1 thru min(n, length of xs) of xs
        else
            {}
        end if
    else if string is c then
        if 0 < n then
            text 1 thru min(n, length of xs) of xs
        else
            ""
        end if
    else if script is c then
        set ys to {}
        repeat with i from 1 to n
            set v to xs's |λ|()
            if missing value is v then
                return ys
            else
                set end of ys to v
            end if
        end repeat
        return ys
    else
        missing value
    end if
end take

-- Tuple (,) :: a -> b -> (a, b)
on Tuple(a, b)
    {type:"Tuple", |1|:a, |2|:b, length:2}
end Tuple

-- unzip :: [(a,b)] -> ([a],[b])
on unzip(xys)
    set xs to {}
    set ys to {}
    repeat with xy in xys
        set end of xs to |1| of xy
        set end of ys to |2| of xy
    end repeat
    return Tuple(xs, ys)
end unzip

-- zip :: [a] -> [b] -> [(a, b)]
on zip(xs, ys)
    zipWith(Tuple, xs, ys)
end zip

-- zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
on zipWith(f, xs, ys)
    set lng to min(|length|(xs), |length|(ys))
    if 1 > lng then return {}
    set xs_ to take(lng, xs) -- Allow for non-finite
    set ys_ to take(lng, ys) -- generators like cycle etc
    set lst to {}
    tell mReturn(f)
        repeat with i from 1 to lng
            set end of lst to |λ|(item i of xs_, item i of ys_)
        end repeat
        return lst
    end tell
end zipWith


def bubbleSort(target) {
  __loop(fn {
    var changed := false
    for i in 0..(target.size() - 2) {
      def [a, b] := target(i, i + 2)
      if (a > b) {
        target(i, i + 2) := [b, a]
        changed := true
      }
    }
    changed
  })
}


;; sorts a vector of objects in place
;; proc is an user defined comparison procedure

(define (bubble-sort V proc)
(define length (vector-length V))
    (for* ((i (in-range 0 (1- length))) (j (in-range (1+ i) length)))
    (unless (proc (vector-ref V i) (vector-ref V j)) (vector-swap! V i j)))
    V)

(define V #( albert antoinette elvis zen simon))
(define (sort/length a b) ;; sort by string length
    (< (string-length a) (string-length b)))

(bubble-sort V sort/length)
    → #(zen simon elvis albert antoinette)


sortDisjoint: function [data, indices][
    result: new data
    inds: new indices
    sort 'inds

    vals: new []
    loop inds 'i -> 'vals ++ result\[i]
    sort 'vals

    loop.with:'j inds 'i -> result\[i]: vals\[j]
    return result
]

d: [7 6 5 4 3 2 1 0]
print sortDisjoint d [6 1 7]


Sort_disjoint_sublist(Values, Indices){
    A := [], B:=[], C := [], D := []
    for k, v in Indices
        A[v] := 1 , B[Values[v]] := v
    for k, v in A
        C.Push(k)
    for k, v in B
        D.Push(k)
    for k, v in D
        Values[C[A_Index]] := D[A_Index]
    return Values
}


      INSTALL @lib$+"SORTLIB"
      Sort% = FN_sortinit(0,0) : REM Ascending

      DIM list%(7) : list%() = 7, 6, 5, 4, 3, 2, 1, 0
      DIM indices%(2) : indices%() = 6, 1, 7

      PROCsortdisjoint(list%(), indices%())
      PRINT FNshowlist(list%())
      END

      DEF PROCsortdisjoint(l%(), i%())
      LOCAL C%, i%, n%, t%()
      n% = DIM(i%(),1)
      DIM t%(n%)
      FOR i% = 0 TO n%
        t%(i%) = l%(i%(i%))
      NEXT
      C% = n% + 1
      CALL Sort%, i%(0)
      CALL Sort%, t%(0)
      FOR i% = 0 TO n%
        l%(i%(i%)) = t%(i%)
      NEXT
      ENDPROC

      DEF FNshowlist(l%())
      LOCAL i%, o$
      o$ = "["
      FOR i% = 0 TO DIM(l%(),1)
        o$ += STR$(l%(i%)) + ", "
      NEXT
      = LEFT$(LEFT$(o$)) + "]"


  [Bubble sort demo for Rosetta Code website]
  [EDSAC program. Initial Orders 2]

  [Sorts a list of double-word integers.
   List must be loaded at an even address.
   First item gives number of items to follow.
   Address of list is placed in location 49.
   List can then be referred to with code letter L.]
          T49K
          P300F [<---------- address of list here]

  [Subroutine R2, reads positive integers during input of orders.
   Items separated by F; list ends with #TZ.]
  [email protected]@[email protected]@E13Z

  [Tell R2 where to store integers it reads from tape.]
        T    #L  ['T m D' in documentation, but this also works]

  [Lists of integers, comment out all except one]
  [10 integers from digits of pi]
  10F314159F265358F979323F846264F338327F950288F419716F939937F510582F097494#TZ

  [32 integers from digits of e ]
  [32F
   27182818F28459045F23536028F74713526F62497757F24709369F99595749F66967627F
   72407663F03535475F94571382F17852516F64274274F66391932F00305992F18174135F
   96629043F57290033F42952605F95630738F13232862F79434907F63233829F88075319F
   52510190F11573834F18793070F21540891F49934884F16750924F47614606F68082264#TZ]

  [Library subroutine P7, prints positive integer at 0D.
   35 locations; load at aneven address.]
        T  56 K
  [email protected]#@[email protected]@[email protected]@SFLDUFOFFFSFL4F
  [email protected]@XFT28#[email protected][email protected]@

  [The EDSAC code below implements the following Pascal program,
   where the integers to be sorted are in a 1-based array x.
   Since the assembler used (EdsacPC by Martin Campbell-Kelly)
   doesn't allow square brackets inside comments, they are
   replaced here by curly brackets.]
  [
    swapped := true;
    j := n; // number of items
    while (swapped and (j >= 2)) do begin
      swapped := false;
      for i := 1 to j - 1 do begin
        // Using temp in the comparison makes the EDSAC code a bit simpler
        temp := x{i};
        if (x{i + 1} < temp) then begin
          x{i} := x{i + 1};
          x{i + 1} := temp;
          swapped := true;
        end;
      end;
      dec(j);
    end;
  ]
    [Main routine]
        T 100 K
        G     K
    [0] P F P F [double-word temporary store]
    [2] P     F [flag for swapped, >= 0 if true, < 0 if false]
    [3] P     F ['A' order for x{j}; implicitly defines j]
    [4] P   2 F [to change list index by 1, i.e.change address by 2]
    [5] A    #L ['A' order for number of items]
    [6] A   2#L ['A' order for x{1}]
    [7] A   4#L ['A' order for x{2}]
    [8] I2046 F [add to convert 'A' order to 'T' and dec address by 2]
    [9] K4096 F [(1) minimum 17-bit value (2) teleprinter null]
   [10] P     D [constant 1, used in printing]
   [11] #     F [figure shift]
   [12] &     F [line feed]
   [13] @     F [carriage return]

       [Enter here with acc = 0]
   [14] T   2 @ [swapped := true]
        A     L [get count, n in Pascal program above]
        L   1 F [times 4 by shifting]
        A   5 @ [make 'A' order for x{n}; initializes j := n]

       [Start 'while' loop of Pascal program.
        Here acc = 'A' order for x{j}]
   [18] U   3 @ [update j]
        S   7 @ [subtract 'A' order for x{2}]
        G  56 @ [if j < 2 then done]
        T     F [acc := 0]
        A   2 @ [test for swapped, acc >= 0 if so]
        G  56 @ [if not swapped then done]
        A   9 @ [change acc from >= 0 to < 0]
        T   2 @ [swapped := false until swap occurs]
        A   6 @ ['A' order for x{1}; initializes i := 1]

       [Start 'for' loop of Pascal program.
        Here acc = 'A' order for x{i}]
   [27] U  36 @ [store order]
        S   3 @ [subtract 'A' order for x{j}]
        E  52 @ [out of 'for' loop if i >= j]
        T     F [clear acc]
        A  36 @ [load 'A' order for x{i}]
        A   4 @ [inc address by 2]
        U  38 @ [plant 'A' order for x{i + 1}]
        A   8 @ ['A' to 'T', and dec address by 2]
        T  42 @ [plant 'T' order for x{i}]
   [36] A    #L [load x{i}; this order implicitly defines i]
        T    #@ [temp := x{i}]
   [38] A    #L [load x{i + 1}]
        S    #@ [acc := x{i + 1} - temp]
        E  49 @ [don't swap if x{i + 1} >= temp]

       [Here to swap x{i} and x{i + 1}]
        A    #@ [restore acc := x{i + 1} after test]
   [42] T    #L [x{i} := x{i + 1}]
        A  42 @ [load 'T' order for x{i}]
        A   4 @ [inc address by 2]
        T  47 @ [plant 'T' order for x{i + 1}]
        A    #@ [load temp]
   [47] T    #L [to x{i + 1}]
        T   2 @ [swapped := 0 (true)]

   [49] T     F [clear acc]
        A  38 @ [load 'A' order for x{i + 1}]
        G  27 @ [loop (unconditional) to inc i]

   [52] T     F
        A   3 @ [load 'A' order for x{j}]
        S   4 @ [dec address by 2]
        G  18 @ [loop (unconditional) to dec j]

       [Print the sorted list of integers]
   [56] O  11 @ [figure shift]
        T     F [clear acc]
        A   5 @ [load 'A' order for head of list]
        T  65 @ [plant in code below]
        S     L [load negative number of items]
   [61] T     @ [use first word of temp store for count]
        A  65 @ [load 'A' order for item]
        A   4 @ [inc address by 2]
        T  65 @ [store back]
   [65] A    #L [load next item in list]
        T     D [to 0D for printing]
   [67] A  67 @ [for subroutine return]
        G  56 F [print integer, clears acc]
        O  13 @ [print CR]
        O  12 @ [print LF]
        A     @ [negative count]
        A  10 @ [add 1]
        G  61 @ [loop back till count = 0]
   [74] O   9 @ [null to flush teleprinter buffer]
        Z     F [stop]
        E  14 Z [define entry point]
        P     F [acc = 0 on entry]


class
    APPLICATION
create
    make

feature
    make
            -- Create and print sorted set
        do
            create my_set.make
            my_set.put_front (2)
            my_set.put_front (6)
            my_set.put_front (1)
            my_set.put_front (5)
            my_set.put_front (3)
            my_set.put_front (9)
            my_set.put_front (8)
            my_set.put_front (4)
            my_set.put_front (10)
            my_set.put_front (7)
            print ("Before: ")
            across my_set as ic loop print (ic.item.out + " ")  end
            print ("%NAfter : ")
            my_set.sort
            across my_set as ic loop print (ic.item.out + " ")  end
        end

    my_set: MY_SORTED_SET [INTEGER]
            -- Set to be sorted
end


7 6 5 4 3 2 1 0:?values
& 6 1 7:?indices
& 0:?sortedValues:?sortedIndices
&   whl
  ' ( !indices:%?i ?indices
    & !values:? [!i %@?value ?
    & (!value.)+!sortedValues:?sortedValues
    & (!i.)+!sortedIndices:?sortedIndices
    )
&   whl
  ' ( !sortedIndices:(?i.)+?sortedIndices
    & !values:?A [!i %@? ?Z
    & !sortedValues:(?value.)+?sortedValues
    & !A !value !Z:?values
    )
& out$!values;


#include <stdio.h>

/* yes, bubble sort */
void bubble_sort(int *idx, int n_idx, int *buf)
{
        int i, j, tmp;
#define for_ij for (i = 0; i < n_idx; i++) for (j = i + 1; j < n_idx; j++)
#define sort(a, b) if (a < b) { tmp = a; a = b; b = tmp;}
        for_ij { sort(idx[j], idx[i]);          }
        for_ij { sort(buf[idx[j]], buf[idx[i]]);}
#undef for_ij
#undef sort
}

int main()
{
        int values[] = {7, 6, 5, 4, 3, 2, 1, 0};
        int idx[] = {6, 1, 7};
        int i;

        printf("before sort:\n");
        for (i = 0; i < 8; i++)
                printf("%d ", values[i]);

        printf("\n\nafter sort:\n");
        bubble_sort(idx, 3, values);

        for (i = 0; i < 8; i++)
                printf("%d ", values[i]);
        printf("\n");

        return 0;
}


import system'routines;
import extensions;

extension op
{
    bubbleSort()
    {
        var list := self.clone();

        bool madeChanges := true;
        int itemCount := list.Length;
        while (madeChanges)
        {
            madeChanges := false;
            itemCount -= 1;
            for(int i := 0, i < itemCount, i += 1)
            {
                if (list[i] > list[i + 1])
                {
                    list.exchange(i,i+1);
                    madeChanges := true
                }
            }
        };

        ^ list
    }
}

public program()
{
    var list := new int[]{3, 7, 3, 2, 1, -4, 10, 12, 4};
    console.printLine(list.bubbleSort().asEnumerable())
}


defmodule Sort do
  def bsort(list) when is_list(list) do
    t = bsort_iter(list)

    if t == list, do: t, else: bsort(t)
  end

  def bsort_iter([x, y | t]) when x > y, do: [y | bsort_iter([x | t])]
  def bsort_iter([x, y | t]), do: [x | bsort_iter([y | t])]
  def bsort_iter(list), do: list
end


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

public class Test
{
    public static void Main()
    {
        var list = new List<int>{ 7, 6, 5, 4, 3, 2, 1, 0 };
        list.SortSublist(6, 1, 7);
        Console.WriteLine(string.Join(", ", list));
    }
}

public static class Extensions
{
    public static void SortSublist<T>(this List<T> list, params int[] indices)
        where T : IComparable<T>
    {
        var sublist = indices.OrderBy(i => i)
            .Zip(indices.Select(i => list[i]).OrderBy(v => v),
                (Index, Value) => new { Index, Value });

        foreach (var entry in sublist) {
            list[entry.Index] = entry.Value;
        }
    }

}


#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>

template <typename ValueIterator, typename IndicesIterator>
void sortDisjoint(ValueIterator valsBegin, IndicesIterator indicesBegin,
		  IndicesIterator indicesEnd) {
    std::vector<int> temp;

    for (IndicesIterator i = indicesBegin; i != indicesEnd; ++i)
        temp.push_back(valsBegin[*i]); // extract

    std::sort(indicesBegin, indicesEnd); // sort
    std::sort(temp.begin(), temp.end()); // sort a C++ container

    std::vector<int>::const_iterator j = temp.begin();
    for (IndicesIterator i = indicesBegin; i != indicesEnd; ++i, ++j)
        valsBegin[*i] = *j; // replace
}

int main()
{
    int values[] = { 7, 6, 5, 4, 3, 2, 1, 0 };
    int indices[] = { 6, 1, 7 };

    sortDisjoint(values, indices, indices+3);

    std::copy(values, values + 8, std::ostream_iterator<int>(std::cout, " "));
    std::cout << "\n";

    return 0;
}


-module( bubble_sort ).

-export( [list/1, task/0] ).

list( To_be_sorted ) -> sort( To_be_sorted, [], true ).

task() ->
	List = "asdqwe123",
	Sorted = list( List ),
	io:fwrite( "List ~p is sorted ~p~n", [List, Sorted] ).

sort( [], Acc, true ) -> lists:reverse( Acc );
sort( [], Acc, false ) -> sort( lists:reverse(Acc), [], true );
sort( [X, Y | T], Acc, _Done ) when X > Y -> sort( [X | T], [Y | Acc], false );
sort( [X | T], Acc, Done ) -> sort( T, [X | Acc], Done ).


(defn disjoint-sort [coll idxs]
  (let [val-subset (keep-indexed #(when ((set idxs) %) %2) coll)
        replacements (zipmap (set idxs) (sort val-subset))]
    (apply assoc coll (flatten (seq replacements)))))


(defun disjoint-sort (values indices)
  "Destructively perform a disjoin sublist sort on VALUES with INDICES."
  (loop :for element :in
     (sort (loop :for index :across indices
              :collect (svref values index))
           '<)
     :for index :across (sort indices '<)
     :do (setf (svref values index) element))
  values)


import std.algorithm, std.range, std.array;

void main() {
    auto data = [7, 6, 5, 4, 3, 2, 1, 0];
    auto indices = [6, 1, 7];

    data.indexed(indices.sort()).sort();

    assert(data == [7, 0, 5, 4, 3, 2, 1, 6]);
}


PROGRAM BUBBLE_SORT

DIM FLIPS%,N,J

DIM A%[100]

BEGIN

! init random number generator
   RANDOMIZE(TIMER)
! fills array A% with random data
   FOR N=1 TO UBOUND(A%,1) DO
     A%[N]=RND(1)*256
   END FOR
! sort array
   FLIPS%=TRUE
   WHILE FLIPS% DO
     FLIPS%=FALSE
     FOR N=1 TO UBOUND(A%,1)-1 DO
        IF A%[N]>A%[N+1] THEN
            SWAP(A%[N],A%[N+1])
            FLIPS%=TRUE
        END IF
     END FOR
   END WHILE
! print sorted array
   FOR N=1 TO UBOUND(A%,1) DO
     PRINT(A%[N];)
   END FOR
   PRINT
END PROGRAM


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

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

puts(1,"Before: ")
pretty_print(1,s,{2})
puts(1,"\nAfter: ")
pretty_print(1,bubble_sort(s),{2})


(define (sort-disjoint values indices)
    (define sorted (list-sort <
    (for/list [(v values) (i (in-naturals))]
	#:when (member i indices)  v)))

    (for/list [(v values) (i (in-naturals))]
	(if (not (member i indices)) v
	(begin0
		(first sorted)
		(set! sorted (rest sorted))))))

(define (task)
	(sort-disjoint '[7 6 5 4 3 2 1 0] {6 1 7}))

(task)
    → (7 0 5 4 3 2 1 6)


import extensions;
import system'routines;
import system'culture;

extension op
{
    sortSublist(indices)
    {
        var subList := indices.orderBy:(x => x)
                            .zipBy(indices.selectBy:(i => self[i])
                                .orderBy:(x => x), (index,val => new{ Index = index; Value = val; }))
                            .toArray();

        var list := self.clone();
        subList.forEach:(r)
        {
            list[r.Index] := r.Value
        };

        ^ list
    }
}

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

    console.printLine(list.sortSublist(new int[]{6, 1, 7}).asEnumerable())
}


defmodule Sort_disjoint do
  def sublist(values, indices) when is_list(values) and is_list(indices) do
    indices2 = Enum.sort(indices)
    selected = select(values, indices2, 0, []) |> Enum.sort
    replace(values, Enum.zip(indices2, selected), 0, [])
  end

  defp select(_, [], _, selected), do: selected
  defp select([val|t], [i|rest], i, selected), do: select(t, rest, i+1, [val|selected])
  defp select([_|t], indices, i, selected), do: select(t, indices, i+1, selected)

  defp replace(values, [], _, list), do: Enum.reverse(list, values)
  defp replace([_|t], [{i,v}|rest], i, list), do: replace(t, rest, i+1, [v|list])
  defp replace([val|t], indices, i, list), do: replace(t, indices, i+1, [val|list])
end

values = [7, 6, 5, 4, 3, 2, 1, 0]
indices = [6, 1, 7]
IO.inspect Sort_disjoint.sublist(values, indices)


## இந்த நிரல் ஒரு பட்டியலில் உள்ள எண்களை Bubble Sort என்ற முறைப்படி ஏறுவரிசையிலும் பின்னர் அதையே இறங்குவரிசையிலும் அடுக்கித் தரும்

## மாதிரிக்கு நாம் ஏழு எண்களை எடுத்துக்கொள்வோம்

எண்கள் = [5, 1, 10, 8, 1, 21, 4, 2]
எண்கள்பிரதி = எண்கள்

பதிப்பி "ஆரம்பப் பட்டியல்:"
பதிப்பி எண்கள்

நீளம் = len(எண்கள்)
குறைநீளம் = நீளம் - 1

@(குறைநீளம் != -1) வரை
  மாற்றம் = -1
  @(எண் = 0, எண் < குறைநீளம், எண் = எண் + 1) ஆக
    முதலெண் = எடு(எண்கள், எண்)
    இரண்டாமெண் = எடு(எண்கள், எண் + 1)
    @(முதலெண் > இரண்டாமெண்) ஆனால்

      ## பெரிய எண்களை ஒவ்வொன்றாகப் பின்னே நகர்த்துகிறோம்

      வெளியேஎடு(எண்கள், எண்)
      நுழைக்க(எண்கள், எண், இரண்டாமெண்)
      வெளியேஎடு(எண்கள், எண் + 1)
      நுழைக்க(எண்கள், எண் + 1, முதலெண்)
      மாற்றம் = எண்
    முடி
  முடி
  குறைநீளம் = மாற்றம்
முடி

பதிப்பி "ஏறு வரிசையில் அமைக்கப்பட்ட பட்டியல்:"
பதிப்பி எண்கள்

## இதனை இறங்குவரிசைக்கு மாற்றுவதற்கு எளிய வழி

தலைகீழ்(எண்கள்)

## இப்போது, நாம் ஏற்கெனவே எடுத்துவைத்த எண்களின் பிரதியை Bubble Sort முறைப்படி இறங்குவரிசைக்கு மாற்றுவோம்

நீளம் = len(எண்கள்பிரதி)
குறைநீளம் = நீளம் - 1

@(குறைநீளம் != -1) வரை
  மாற்றம் = -1
  @(எண் = 0, எண் < குறைநீளம், எண் = எண் + 1) ஆக
    முதலெண் = எடு(எண்கள்பிரதி, எண்)
    இரண்டாமெண் = எடு(எண்கள்பிரதி, எண் + 1)
    @(முதலெண் < இரண்டாமெண்) ஆனால்

      ## சிறிய எண்களை ஒவ்வொன்றாகப் பின்னே நகர்த்துகிறோம்

      வெளியேஎடு(எண்கள்பிரதி, எண்)
      நுழைக்க(எண்கள்பிரதி, எண், இரண்டாமெண்)
      வெளியேஎடு(எண்கள்பிரதி, எண் + 1)
      நுழைக்க(எண்கள்பிரதி, எண் + 1, முதலெண்)
      மாற்றம் = எண்
    முடி
  முடி
  குறைநீளம் = மாற்றம்
முடி

பதிப்பி "இறங்கு வரிசையில் அமைக்கப்பட்ட பட்டியல்:"
பதிப்பி எண்கள்பிரதி


let BubbleSort (lst : list<int>) =
    let rec sort accum rev lst =
        match lst, rev with
        | [], true -> accum |> List.rev
        | [], false -> accum |> List.rev |> sort [] true
        | x::y::tail, _ when x > y -> sort (y::accum) false (x::tail)
        | head::tail, _ -> sort (head::accum) rev tail
    sort [] true lst


-module( sort_disjoint ).

-export( [sublist/2, task/0] ).

sublist( Values, Indices ) ->
	Sorted_indices = lists:sort( Indices ),
	Values_indexes = lists:seq( 1, erlang:length(Values) ),
	{[], [], Indices_values} = lists:foldl( fun indices_values/2, {Values, Sorted_indices, []}, Values_indexes ),
	Sorted_indices_values = lists:zip( Sorted_indices, lists:sort(Indices_values) ),
	{Sorted_values, {[], []}} = lists:mapfoldl( fun merge/2, {Values, Sorted_indices_values}, Values_indexes ),
	Sorted_values.

task() -> sublist( [7, 6, 5, 4, 3, 2, 1, 0], [7, 2, 8] ).

indices_values( Index, {[H | Values], [Index | Indices], Indices_values} ) -> {Values, Indices, [H | Indices_values]};
indices_values( _Index, {[_H | Values], Indices, Indices_values} ) -> {Values, Indices, Indices_values}.

merge( Index, {[_H | Values], [{Index, Value} | Sorted_indices_values]} ) -> {Value, {Values, Sorted_indices_values}};
merge( _Index, {[H | Values], Sorted_indices_values} ) -> {H, {Values, Sorted_indices_values}}.


USING: fry kernel locals math math.order sequences
sequences.private ;
IN: rosetta.bubble

<PRIVATE

:: ?exchange ( i seq quot -- ? )
    i i 1 + [ seq nth-unsafe ] [email protected] quot call +gt+ = :> doit?
    doit? [ i i 1 + seq exchange ] when
    doit? ; inline

: 1pass ( seq quot -- ? )
    [ [ length 1 - iota ] keep ] dip
    '[ _ _ ?exchange ] [ or ] map-reduce ; inline

PRIVATE>

: sort! ( seq quot -- )
    over empty?
    [ 2drop ] [ '[ _ _ 1pass ] loop ] if ; inline

: natural-sort! ( seq -- )
    [ <=> ] sort! ;


PROGRAM DISJOINT

DIM LST%[7],INDICES%[2]

DIM L%[7],I%[2],Z%[2]
PROCEDURE SHOWLIST(L%[]->O$)
      LOCAL I%
      O$="["
      FOR I%=0 TO UBOUND(L%,1) DO
        O$=O$+STR$(L%[I%])+", "
      END FOR
      O$=LEFT$(O$,LEN(O$)-2)+"]"
END PROCEDURE

PROCEDURE SORT(Z%[]->Z%[])
   LOCAL N%,P%,FLIPS%
   P%=UBOUND(Z%,1)
   FLIPS%=TRUE
   WHILE FLIPS% DO
      FLIPS%=FALSE
      FOR N%=0 TO P%-1 DO
        IF Z%[N%]>Z%[N%+1] THEN SWAP(Z%[N%],Z%[N%+1]) FLIPS%=TRUE
      END FOR
   END WHILE
END PROCEDURE

PROCEDURE SortDisJoint(L%[],I%[]->L%[])
      LOCAL J%,N%
      LOCAL DIM T%[2]

      N%=UBOUND(I%,1)
      FOR J%=0 TO N% DO
        T%[J%]=L%[I%[J%]]
      END FOR
      SORT(I%[]->I%[])
      SORT(T%[]->T%[])
      FOR J%=0 TO N% DO
        L%[I%[J%]]=T%[J%]
      END FOR
END PROCEDURE

BEGIN
  LST%[]=(7,6,5,4,3,2,1,0)
  INDICES%[]=(6,1,7)
  SortDisJoint(LST%[],INDICES%[]->LST%[])
  ShowList(LST%[]->O$)
  PRINT(O$)
END PROGRAM


include sort.e

function uniq(sequence s)
    sequence out
    out = s[1..1]
    for i = 2 to length(s) do
        if not find(s[i], out) then
            out = append(out, s[i])
        end if
    end for
    return out
end function

function disjointSort(sequence s, sequence idx)
    sequence values
    idx = uniq(sort(idx))
    values = repeat(0, length(idx))
    for i = 1 to length(idx) do
        values[i] = s[idx[i]]
    end for
    values = sort(values)
    for i = 1 to length(idx) do
        s[idx[i]] = values[i]
    end for
    return s
end function

constant data = {7, 6, 5, 4, 3, 2, 1, 0}
constant indexes = {7, 2, 8}


let sortDisjointSubarray data indices =
  let indices = Set.toArray indices // creates a sorted array
  let result = Array.copy data
  Array.map (Array.get data) indices
  |> Array.sort
  |> Array.iter2 (Array.set result) indices
  result

printfn "%A" (sortDisjointSubarray [|7;6;5;4;3;2;1;0|] (set [6;1;7]))


defer bubble-test
' > is bubble-test

: bubble { addr cnt -- }
  cnt 1 do
    addr cnt i - cells bounds do
      i [email protected] bubble-test if i [email protected] swap i 2! then
    cell +loop
  loop ;


SUBROUTINE Bubble_Sort(a)
  REAL, INTENT(in out), DIMENSION(:) :: a
  REAL :: temp
  INTEGER :: i, j
  LOGICAL :: swapped

  DO j = SIZE(a)-1, 1, -1
    swapped = .FALSE.
    DO i = 1, j
      IF (a(i) > a(i+1)) THEN
        temp = a(i)
        a(i) = a(i+1)
        a(i+1) = temp
        swapped = .TRUE.
      END IF
    END DO
    IF (.NOT. swapped) EXIT
  END DO
END SUBROUTINE Bubble_Sort


: disjoint-sort! ( values indices -- values' )
    over <enumerated> nths unzip swap [ natural-sort ] [email protected]
    pick [ set-nth ] curry 2each ;


program Example
  implicit none

  integer :: array(8) = (/ 7, 6, 5, 4, 3, 2, 1, 0 /)
  integer :: indices(3) = (/ 7, 2, 8 /)

! In order to make the output insensitive to index order
! we need to sort the indices first
  call Isort(indices)

! Should work with any sort routine as long as the dummy
! argument array has been declared as an assumed shape array
! Standard insertion sort used in this example
  call Isort(array(indices))

  write(*,*) array

contains

subroutine Isort(a)
  integer, intent(in out) :: a(:)
  integer :: temp
  integer :: i, j

  do i = 2, size(a)
     j = i - 1
     temp = a(i)
     do while (j>=1 .and. a(j)>temp)
        a(j+1) = a(j)
        j = j - 1
     end do
     a(j+1) = temp
  end do

end subroutine Isort
end program Example


dim as integer value(0 to 7) = {7, 6, 5, 4, 3, 2, 1, 0}
dim as integer index(0 to 2) = {6, 1, 7}, i

for i = 0 to 1
    if value(index(i))>value(index(i+1)) then
        swap value(index(i)), value(index(i+1))
    end if
next i

for i  = 0 to 7
    print value(i);
next i : print


' version 21-10-2016
' compile with: fbc -s console
' for boundry checks on array's compile with: fbc -s console -exx

Sub bubblesort(bs() As Long)
    ' sort from lower bound to the highter bound
    ' array's can have subscript range from -2147483648 to +2147483647
    Dim As Long lb = LBound(bs)
    Dim As Long ub = UBound(bs)
    Dim As Long done, i

    Do
        done = 0
        For i = lb To ub -1
            ' replace "<" with ">" for downwards sort
            If bs(i) > bs(i +1) Then
                Swap bs(i), bs(i +1)
                done = 1
            End If
        Next
    Loop Until done = 0

End Sub

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

Dim As Long i, array(-7 To 7)

Dim As Long a = LBound(array), b = UBound(array)

Randomize Timer
For i = a To b : array(i) = i  : Next
For i = a To b ' little shuffle
    Swap array(i), array(Int(Rnd * (b - a +1)) + a)
Next

Print "unsort ";
For i = a To b : Print Using "####"; array(i); : Next : Print
bubblesort(array())  ' sort the array
Print "  sort ";
For i = a To b : Print Using "####"; array(i); : Next : Print

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


package main

import (
    "fmt"
    "sort"
)

func main() {
    // givens
    values := []int{7, 6, 5, 4, 3, 2, 1, 0}
    indices := map[int]int{6: 0, 1: 0, 7: 0}

    orderedValues := make([]int, len(indices))
    orderedIndices := make([]int, len(indices))
    i := 0
    for j := range indices {
        // validate that indices are within list boundaries
        if j < 0 || j >= len(values) {
            fmt.Println("Invalid index: ", j)
            return
        }
        // extract elements to sort
        orderedValues[i] = values[j]
        orderedIndices[i] = j
        i++
    }
    // sort
    sort.Ints(orderedValues)
    sort.Ints(orderedIndices)

    fmt.Println("initial:", values)
    // replace sorted values
    for i, v := range orderedValues {
        values[orderedIndices[i]] = v
    }
    fmt.Println("sorted: ", values)
}


def sparseSort = { a, indices = ([] + (0..<(a.size()))) ->
    indices.sort().unique()
    a[indices] = a[indices].sort()
    a
}


(fun bubbles (vs)
  (let done? F n (len vs))

  (while (not done?)
    (set done? T n (- n 1))

    (for (n i)
      (let x (# vs i) j (+ i 1) y (# vs j))
      (if (> x y) (set done? F (# vs i) y (# vs j) x))))

  vs)

(bubbles '(2 1 3))
---
(1 2 3)


Public Sub Main()
Dim byToSort As Byte[] = [249, 28, 111, 36, 171, 98, 29, 448, 44, 147, 154, 46, 102, 183, 24,
                          120, 19, 123, 2, 17, 226, 11, 211, 25, 191, 205, 77]
Dim byCount As Byte
Dim bSorting As Boolean

Print "To sort: -"
ShowWorking(byToSort)
Print
Repeat
  bSorting = False
  For byCount = 0 To byToSort.Max - 1
    If byToSort[byCount] > byToSort[byCount + 1] Then
      Swap byToSort[byCount], byToSort[byCount + 1]
      bSorting = True
    Endif
  Next
  If bSorting Then ShowWorking(byToSort)
Until bSorting = False
End
'-----------------------------------------
Public Sub ShowWorking(byToSort As Byte[])
Dim byCount As Byte

For byCount = 0 To byToSort.Max
  Print Str(byToSort[byCount]);
  If byCount <> byToSort.Max Then Print ",";
Next

Print

End


import Control.Monad
import qualified Data.Array as A
import Data.Array.IArray
import Data.Array.ST
import Data.List
import Data.List.Utils

-- Partition 'xs' according to whether their element indices are in 'is'.  Sort
-- the sublist corresponding to 'is', merging the result with the remainder of
-- the list.
disSort1
  :: (Ord a, Num a, Enum a, Ord b)
  => [b] -> [a] -> [b]
disSort1 xs is =
  let is_ = sort is
      (sub, rest) = partition ((`elem` is_) . fst) $ zip [0 ..] xs
  in map snd . merge rest . zip is_ . sort $ map snd sub

-- Convert the list to an array.  Extract the sublist corresponding to the
-- indices 'is'.  Sort the sublist, replacing those elments in the array.
disSort2
  :: (Ord a)
  => [a] -> [Int] -> [a]
disSort2 xs is =
  let as = A.listArray (0, length xs - 1) xs
      sub = zip (sort is) . sort $ map (as !) is
  in elems $ as // sub

-- Similar to disSort2, but using mutable arrays.  The sublist is updated
-- "in place", rather than creating a new array.  However, this is not visible
-- to a caller.
disSort3 :: [Int] -> [Int] -> [Int]
disSort3 xs is =
  elems . runSTUArray $
  do as <- newListArray (0, length xs - 1) xs
     sub <- (zip (sort is) . sort) Control.Applicative.<$> mapM (readArray as) is
     mapM_ (uncurry (writeArray as)) sub
     return as

main :: IO ()
main = do
  let xs = [7, 6, 5, 4, 3, 2, 1, 0]
      is = [6, 1, 7]
  print $ disSort1 xs is
  print $ disSort2 xs is
  print $ disSort3 xs is


package main

import "fmt"

func main() {
    list := []int{31, 41, 59, 26, 53, 58, 97, 93, 23, 84}
    fmt.Println("unsorted:", list)

    bubblesort(list)
    fmt.Println("sorted!  ", list)
}

func bubblesort(a []int) {
    for itemCount := len(a) - 1; ; itemCount-- {
        hasChanged := false
        for index := 0; index < itemCount; index++ {
            if a[index] > a[index+1] {
                a[index], a[index+1] = a[index+1], a[index]
                hasChanged = true
            }
        }
        if hasChanged == false {
            break
        }
    }
}


def makeSwap = { a, i, j = i+1 -> print "."; a[[i,j]] = a[[j,i]] }

def checkSwap = { a, i, j = i+1 -> [(a[i] > a[j])].find { it }.each { makeSwap(a, i, j) } }

def bubbleSort = { list ->
    boolean swapped = true
    while (swapped) { swapped = (1..<list.size()).any { checkSwap(list, it-1) } }
    list
}


link sort # get the 'isort' procedure for sorting a list

procedure sortDisjoint (items, indices)
  indices := isort (indices) # sort indices into a list
  result := copy (items)
  values := []
  every put (values, result[!indices])
  values := isort (values)
  every result[!indices] := pop (values)
  return result
end

procedure main ()
  # set up and do the sort
  items := [7, 6, 5, 4, 3, 2, 1, 0]
  indices := set(7, 2, 8) # note, Icon lists 1-based
  result := sortDisjoint (items, indices)
  # display result
  every writes (!items || " ")
  write ()
  every writes (!indices || " ")
  write ()
  every writes (!result || " ")
  write ()
end


List disjointSort := method(indices,
    sortedIndices := indices unique sortInPlace
    sortedValues := sortedIndices map(idx,at(idx)) sortInPlace
    sortedValues foreach(i,v,atPut(sortedIndices at(i),v))
    self
)

list(7,6,5,4,3,2,1,0) disjointSort(list(6,1,7)) println


bsort :: Ord a => [a] -> [a]
bsort s = case _bsort s of
               t | t == s    -> t
                 | otherwise -> bsort t
  where _bsort (x:x2:xs) | x > x2    = x2:(_bsort (x:xs))
                         | otherwise = x:(_bsort (x2:xs))
        _bsort s = s


class BubbleSort {
  @:generic
  public static function sort<T>(arr:Array<T>) {
    var madeChanges = false;
    var itemCount = arr.length;
    do {
      madeChanges = false;
      itemCount--;
      for (i in 0...itemCount) {
        if (Reflect.compare(arr[i], arr[i + 1]) > 0) {
          var temp = arr[i + 1];
          arr[i + 1] = arr[i];
          arr[i] = temp;
          madeChanges = true;
        }
      }
    } while (madeChanges);
  }
}

class Main {
  static function main() {
    var integerArray   = [1, 10, 2, 5, -1, 5, -19, 4, 23, 0];
    var floatArray = [1.0, -3.2, 5.2, 10.8, -5.7, 7.3,
                      3.5, 0.0, -4.1, -9.5];
    var stringArray = ['We', 'hold', 'these', 'truths', 'to',
                       'be', 'self-evident', 'that', 'all',
                       'men', 'are', 'created', 'equal'];
    Sys.println('Unsorted Integers: ' + integerArray);
    BubbleSort.sort(integerArray);
    Sys.println('Sorted Integers:   ' + integerArray);
    Sys.println('Unsorted Floats:   ' + floatArray);
    BubbleSort.sort(floatArray);
    Sys.println('Sorted Floats:     ' + floatArray);
    Sys.println('Unsorted Strings:  ' + stringArray);
    BubbleSort.sort(stringArray);
    Sys.println('Sorted Strings:    ' + stringArray);
  }
}


import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class Disjoint {
    public static <T extends Comparable<? super T>> void sortDisjoint(
            List<T> array, int[] idxs) {
        Arrays.sort(idxs);
        List<T> disjoint = new ArrayList<T>();
        for (int idx : idxs) {
            disjoint.add(array.get(idx));
        }
        Collections.sort(disjoint);
        int i = 0;
        for (int idx : idxs) {
            array.set(idx, disjoint.get(i++));
        }
    }

    public static void main(String[] args) {
        List<Integer> list = Arrays.asList(7, 6, 5, 4, 3, 2, 1, 0);
        int[] indices = {6, 1, 7};
        System.out.println(list);
        sortDisjoint(list, indices);
        System.out.println(list);
    }
}


SUBROUTINE Bubble_Sort(a)
  REAL :: a(1)

  DO j = LEN(a)-1, 1, -1
    swapped = 0
    DO i = 1, j
      IF (a(i) > a(i+1)) THEN
        temp = a(i)
        a(i) = a(i+1)
        a(i+1) = temp
        swapped = 1
      ENDIF
    ENDDO
    IF (swapped == 0) RETURN
  ENDDO
END


procedure main()                     #: demonstrate various ways to sort a list and string
   demosort(bubblesort,[3, 14, 1, 5, 9, 2, 6, 3],"qwerty")
end

procedure bubblesort(X,op)           #: return sorted list
local i,swapped

   op := sortop(op,X)                # select how and what we sort

   swapped := 1
   while \swapped := &null do         # the sort
      every  i := 2 to *X do
         if op(X[i],X[i-1]) then
            X[i-1] :=: X[swapped := i]
   return X
end


function sort_disjoint(values, indices) {
  var sublist = [];
  indices.sort(function(a, b) { return a > b; });

  for (var i = 0; i < indices.length; i += 1) {
    sublist.push(values[indices[i]]);
  }

  sublist.sort(function(a, b) { return a < b; });

  for (var i = 0; i < indices.length; i += 1) {
    values[indices[i]] = sublist.pop();
  }

  return values;
}


def setpaths(indices; values):
  reduce range(0; indices|length) as $i
    (.; .[indices[$i]] = values[$i]);

def disjointSort(indices):
  (indices|unique) as $ix   # "unique" sorts
  # Set $sorted to the sorted array of values at $ix:
  | ([ .[ $ix[] ] ] | sort) as $sorted
  | setpaths( $ix; $sorted) ;


function sortselected(a::AbstractVector{<:Real}, s::AbstractVector{<:Integer})
    sel = unique(sort(s))
    if sel[1] < 1 || length(a) < sel[end]
        throw(BoundsError())
    end
    b = collect(copy(a))
    b[sel] = sort(b[sel])
    return b
end

a = [7, 6, 5, 4, 3, 2, 1, 0]
sel = [7, 2, 8]
b = sortselected(a, sel)

println("Original: $a\n\tsorted on $sel\n -> sorted array: $b")


List do(
  bubblesort := method(
    t := true
    while( t,
      t := false
      for( j, 0, self size - 2,
        if( self at( j ) start > self at( j+1 ) start,
          self swapIndices( j,j+1 )
          t := true
        )
      )
    )
    return( self )
  )
)


bubbleSort=:  (([ (<. , >.) {[email protected]]) , }[email protected]])/^:_


  {@[x;[email protected]<y;:;[email protected]<a:[email protected]]}[7 6 5 4 3 2 1 0;6 1 7]
7 0 5 4 3 2 1 6


// version 1.1.51

/* in place sort */
fun IntArray.sortDisjoint(indices: Set<Int>) {
    val sortedSubset = this.filterIndexed { index, _ -> index in indices }.sorted()
    if (sortedSubset.size < indices.size)
        throw IllegalArgumentException("Argument set contains out of range indices")
    indices.sorted().forEachIndexed { index, value -> this[value] = sortedSubset[index] }
}

fun main(args: Array<String>) {
    val values = intArrayOf(7, 6, 5, 4, 3, 2, 1, 0)
    val indices = setOf(6, 1, 7)
    println("Original array : ${values.asList()} sorted on indices $indices")
    values.sortDisjoint(indices)
    println("Sorted array   : ${values.asList()}")
}


#!/bin/ksh

# Sort disjoint sublist

#	# Variables:
#
typeset -a arr_Val=( 7 6 5 4 3 2 1 0 )
typeset -a arr_Ind=( 6 1 7 )
integer i

#	# Functions:
#
#       # Function _insertionSort(array) - Insertion sort of array of integers
#
function _insertionSort {
	typeset _arr ; nameref _arr="$1"
	typeset _i _j _val ; integer _i _j _val

	for (( _i=1; _i<${#_arr[*]}; _i++ )); do
		_val=${_arr[_i]}
		(( _j = _i - 1 ))
		while (( _j>=0 && _arr[_j]>_val )); do
			_arr[_j+1]=${_arr[_j]}
			(( _j-- ))
		done
		_arr[_j+1]=${_val}
	done
}

 ######
# main #
 ######
print "Before sort: ${arr_Val[*]}"

typeset -a arr_2sort
for ((i=0; i<${#arr_Ind[*]}; i++)); do
	arr_2sort+=( ${arr_Val[${arr_Ind[i]}]} )
done

_insertionSort arr_2sort	# Sort the chosen values
_insertionSort arr_Ind		# Sort the indices

for ((i=0; i<${#arr_Ind[*]}; i++)); do
	arr_Val[${arr_Ind[i]}]=${arr_2sort[i]}
done

print "After  sort: ${arr_Val[*]}"


(defn bubble-sort!
  [arr]
  (def arr-len (length arr))
  (when (< arr-len 2)
    (break arr))
  # at this point there are two or more elements
  (loop [i :down-to [(dec arr-len) 0]]
    (for j 0 i
      (def left-elt (get arr j))
      (def right-elt (get arr (inc j)))
      (when (> left-elt right-elt)
        (put arr j right-elt)
        (put arr (inc j) left-elt))))
  arr)

(comment

  (let [n 100
        arr (seq [i :range [0 n]]
              (* n (math/random)))]
    (deep= (bubble-sort! (array ;arr))
           (sort (array ;arr))))
  # => true

  )


public static <E extends Comparable<? super E>> void bubbleSort(E[] comparable) {
    boolean changed = false;
    do {
        changed = false;
        for (int a = 0; a < comparable.length - 1; a++) {
            if (comparable[a].compareTo(comparable[a + 1]) > 0) {
                E tmp = comparable[a];
                comparable[a] = comparable[a + 1];
                comparable[a + 1] = tmp;
                changed = true;
            }
        }
    } while (changed);
}


values  = { 7, 6, 5, 4, 3, 2, 1, 0 }
indices = { 6, 1, 7 }

i = 1						-- discard duplicates
while i < #indices do
    j = i + 1
    while j < #indices do
	if indices[i] == indices[j] then
  	    table.remove( indices[j] )
	end
	j = j + 1
    end
    i = i + 1
end

for i = 1, #indices do
    indices[i] = indices[i] + 1      -- the tables of lua are one-based
end

vals = {}
for i = 1, #indices do
    vals[i] = values[ indices[i] ]
end

table.sort( vals )
table.sort( indices )

for i = 1, #indices do
    values[ indices[i] ] = vals[i]
end

for i = 1, #values do
    io.write( values[i], "  " )
end


sortDisjoint := proc(values, indices::set)
	local vals,inds,i:
	vals := sort([seq(values[i], i in indices)]):
	inds := sort(convert(indices, Array)):
	for i to numelems(vals) do
		values(inds[i]) := vals[i]:
	od:
end proc:
tst := Array([7,6,5,4,3,2,1,0]):
sortDisjoint(tst,{7,2,8});


Values = { 7, 6, 5, 4, 3, 2, 1, 0} ; Indices = { 7, 2, 8 };
Values[[Sort[Indices]]] = Sort[Values[[Indices]]];
Values


Array.prototype.bubblesort = function() {
    var done = false;
    while (!done) {
        done = true;
        for (var i = 1; i<this.length; i++) {
            if (this[i-1] > this[i]) {
                done = false;
                [this[i-1], this[i]] = [this[i], this[i-1]]
            }
        }
    }
    return this;
}


def bubble_sort:
  def swap(i;j): .[i] as $x | .[i]=.[j] | .[j]=$x;

  # input/output: [changed, list]
  reduce range(0; length) as $i
    ( [false, .];
      if $i > 0 and (.[0]|not) then .
      else reduce range(0; (.[1]|length) - $i - 1) as $j
        (.[0] = false;
        .[1] as $list
        | if $list[$j] > $list[$j + 1] then [true, ($list|swap($j; $j+1))]
          else .
          end )
      end  ) | .[1] ;


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

runSample(arg)
return

-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method sortDisjoint(oldList, indices) public static
  newList = oldList.space()
  if indices.words() > 1 then do -- only do work if we need to
    subList = ArrayList()
    idxList = ArrayList()
    -- pick the input list apart
    loop ix = 1 to indices.words()
      iw = indices.word(ix)
      nw = oldList.word(iw)
      -- protect against bad outcomes...
      if iw > oldList.words() then signal ArrayIndexOutOfBoundsException()
      if iw < 1               then signal ArrayIndexOutOfBoundsException()
      subList.add(nw)
      idxList.add(iw)
      end ix
    Collections.sort(subList) -- sort sublist
    Collections.sort(idxList) -- sort indices
    -- put it all back together
    loop kx = 0 to subList.size() - 1
      kk = Rexx subList.get(kx)
      ii = Rexx idxList.get(kx)
      newList = newList.subword(1, ii - 1) kk newList.subword(ii + 1)
      end kx
    end
  return newList

-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method runSample(arg) private static
  parse arg vList ',' iList
  if vList = '' then vList = 7 6 5 4 3 2 1 0
  if iList = '' then iList = 7 2 8
  rList = sortDisjoint(vList, iList)
  say 'In: ' vList.space
  say 'Out:' rList.space
  say 'Idx:' iList.space
  return


  values := [7, 6, 5, 4, 3, 2, 1, 0]
  indices := sortup [6, 1, 7]
  values#indices := sortup values#indices
7 0 5 4 3 2 1 6


import algorithm

proc sortDisjoinSublist[T](data: var seq[T], indices: seq[int]) =
  var indices = indices
  sort indices, cmp[T]

  var values: seq[T] = @[]
  for i in indices: values.add data[i]
  sort values, cmp[T]

  for j, i in indices: data[i] = values[j]

var d = @[7, 6, 5, 4, 3, 2, 1, 0]
sortDisjoinSublist(d, @[6, 1, 7])
echo d


function bubblesort!(arr::AbstractVector)
    for _ in 2:length(arr), j in 1:length(arr)-1
        if arr[j] > arr[j+1]
            arr[j], arr[j+1] = arr[j+1], arr[j]
        end
    end
    return arr
end

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


import java.util.Comparator

fun <T> bubbleSort(a: Array<T>, c: Comparator<T>) {
    var changed: Boolean
    do {
        changed = false
        for (i in 0..a.size - 2) {
            if (c.compare(a[i], a[i + 1]) > 0) {
                val tmp = a[i]
                a[i] = a[i + 1]
                a[i + 1] = tmp
                changed = true
            }
        }
    } while (changed)
}


#import <Foundation/Foundation.h>

@interface DisjointSublistView : NSMutableArray {
  NSMutableArray *array;
  int *indexes;
  int num_indexes;
}
- (instancetype)initWithArray:(NSMutableArray *)a andIndexes:(NSIndexSet *)ind;
@end

@implementation DisjointSublistView
- (instancetype)initWithArray:(NSMutableArray *)a andIndexes:(NSIndexSet *)ind {
  if ((self = [super init])) {
    array = a;
    num_indexes = [ind count];
    indexes = malloc(num_indexes * sizeof(int));
    for (NSUInteger i = [ind firstIndex], j = 0; i != NSNotFound; i = [ind indexGreaterThanIndex:i], j++)
      indexes[j] = i;
  }
  return self;
}
- (void)dealloc {
  free(indexes);
}
- (NSUInteger)count { return num_indexes; }
- (id)objectAtIndex:(NSUInteger)i { return array[indexes[i]]; }
- (void)replaceObjectAtIndex:(NSUInteger)i withObject:(id)x { array[indexes[i]] = x; }
@end

@interface NSMutableArray (SortDisjoint)
- (void)sortDisjointSublist:(NSIndexSet *)indexes usingSelector:(SEL)comparator;
@end
@implementation NSMutableArray (SortDisjoint)
- (void)sortDisjointSublist:(NSIndexSet *)indexes usingSelector:(SEL)comparator {
  DisjointSublistView *d = [[DisjointSublistView alloc] initWithArray:self andIndexes:indexes];
  [d sortUsingSelector:comparator];
}
@end

int main(int argc, const char *argv[]) {
  @autoreleasepool {

    NSMutableArray *a = [@[@7, @6, @5, @4, @3, @2, @1, @0] mutableCopy];
    NSMutableIndexSet *ind = [NSMutableIndexSet indexSet];
    [ind addIndex:6]; [ind addIndex:1]; [ind addIndex:7];
    [a sortDisjointSublist:ind usingSelector:@selector(compare:)];
    NSLog(@"%@", a);

  }
  return 0;
}


{def bubblesort
 {def bubblesort.swap!
  {lambda {:a :n :i}
   {if {> :i :n}
    then :a
    else {bubblesort.swap! {if {> {A.get :i :a} {A.get {+ :i 1} :a}}
                            then {A.set! :i {A.get {+ :i 1} :a}
                                 {A.set! {+ :i 1} {A.get :i :a} :a}}
                            else :a}
                           :n
                           {+ :i 1}} }}}
 {def bubblesort.r
  {lambda {:a :n}
   {if {<= :n 1}
    then :a
    else {bubblesort.r {bubblesort.swap! :a :n 0}
                       {- :n 1}} }}}

 {lambda {:a}
  {bubblesort.r :a {- {A.length :a} 1}}}}
-> bubblesort

{bubblesort {A.new 0  3 86 20 27 67 31 16 37 42  8 47  7 84  5 29}}
-> [0,3,5,7,8,16,20,27,29,31,37,42,47,67,84,86]


let disjoint_sort cmp values indices =
  let temp = Array.map (Array.get values) indices in
  Array.sort cmp temp;
  Array.sort compare indices;
  Array.iteri (fun i j -> values.(j) <- temp.(i)) indices

let () =
  let values = [| 7; 6; 5; 4; 3; 2; 1; 0 |]
  and indices = [| 6; 1; 7 |] in
  disjoint_sort compare values indices;
  Array.iter (Printf.printf " %d") values;
  print_newline()


data = .array~of(7, 6, 5, 4, 3, 2, 1, 0)
-- this could be a list, array, or queue as well because of polymorphism
-- also, ooRexx arrays are 1-based, so using the alternate index set for the
-- problem.
indexes = .set~of(7, 2, 8)
call disjointSorter data, indexes

say "Sorted data is: ["data~toString("l", ", ")"]"

::routine disjointSorter
  use arg data, indexes
  temp = .array~new(indexes~items)
  -- we want to process these in a predictable order, so make an array
  tempIndexes = indexes~makearray
  -- we can't just assign things back in the same order.  The expected
  -- result requires the items be inserted back in first-to-last index
  -- order, so we need to sort the index values too
  tempIndexes~sortWith(.numberComparator~new)
  do index over tempIndexes
     temp~append(data[index])
  end
  -- sort as numbers
  temp~sortwith(.numberComparator~new)

  do i = 1 to tempIndexes~items
     data[tempIndexes[i]] = temp[i]
  end

-- a custom comparator that sorts strings as numeric values rather than
-- strings
::class numberComparator subclass comparator
::method compare
  use strict arg left, right
  -- perform the comparison on the names.  By subtracting
  -- the two and returning the sign, we give the expected
  -- results for the compares
  return (left - right)~sign


    itemCount = 20
    dim item(itemCount)
    for i = 1 to itemCount
        item(i) = int(rnd(1) * 100)
    next i
    print "Before Sort"
    for i = 1 to itemCount
        print item(i)
    next i
    print: print
    counter = itemCount
    do
        hasChanged = 0
        for i = 1 to counter - 1
            if item(i) > item(i + 1) then
                temp = item(i)
                item(i) = item(i + 1)
                item(i + 1) = temp
                hasChanged = 1
            end if
        next i
        counter =counter -1
    loop while hasChanged = 1
    print "After Sort"
    for i = 1 to itemCount
        print item(i)
    next i
end


#include <order/interpreter.h>

#define ORDER_PP_DEF_8sort_disjoint_sublist ORDER_PP_FN(              \
8fn(8L, 8I,                                                           \
    8lets((8I, 8seq_sort(8less, 8tuple_to_seq(8I)))                   \
          (8J,                                                        \
           8seq_sort(8less, 8seq_map(8fn(8X, 8seq_at(8X, 8L)), 8I))), \
          8replace(8L, 8I, 8J))) )

#define ORDER_PP_DEF_8replace ORDER_PP_FN(                   \
8fn(8L, 8I, 8V,                                              \
    8if(8is_nil(8I),                                         \
        8L,                                                  \
        8replace(8seq_set(8seq_head(8I), 8L, 8seq_head(8V)), \
                 8seq_tail(8I), 8seq_tail(8V)))) )

ORDER_PP(
  8sort_disjoint_sublist(8seq(7, 6, 5, 4, 3, 2, 1, 0), 8tuple(6, 1, 7))
)


sortsome(v,which)={
  my(x=sum(i=1,#which,1<<(which[i]-1)),u=vecextract(v,x));
  u=vecsort(u);
  which=vecsort(which);
  for(i=1,#which,v[which[i]]=u[i]);
  v
};


    program disjointsort;

    procedure swap(var a, b: Integer);
    var
    temp: Integer;
    begin
    temp := a;
    a := b;
    b := temp;
    end;

    procedure d_sort(var index,arr:array of integer);
    var
    n,i,j,num:integer;
    begin
    num:=length(index);
    for n:=1 to 2 do
    begin
    for i:=0 to num-1 do
    begin
    for j:=i+1 to num-1 do
    begin
     if n=1 then if index[j]<index[i] then swap(index[j],index[i]);
     if n=2 then if arr[index[j]]<arr[index[i]] then swap(arr[index[j]],arr[index[i]]);
    end;
    end;
    end;
    end;

    var
    i:integer;
    arr  :array[0 .. 7] of integer =(7, 6, 5, 4, 3, 2, 1, 0);
    index:array[0 .. 2] of integer =(6, 1, 7);

    begin
    writeln('Before');
    for i:=0 to 7 do write(arr[i],'  ');
    writeln;
    d_sort(index,arr);
    writeln('After');
    for i:=0 to 7 do write(arr[i],'  ');
    writeln;
    readln;
    end.


Section Header

+ name := BUBBLE_SORT;

- external := `#include <time.h>`;

Section Public

- main <- (
  + a : ARRAY(INTEGER);

  a := ARRAY(INTEGER).create 0 to 100;
  `srand(time(NULL))`;
  0.to 100 do { i : INTEGER;
    a.put `rand()`:INTEGER to i;
  };

  bubble a;

  a.foreach { item : INTEGER;
    item.print;
    '\n'.print;
  };
);

- bubble a : ARRAY(INTEGER) <- (
  + lower, size, t : INTEGER;
  + sorted : BOOLEAN;
  lower := a.lower;
  size := a.upper - lower + 1;
  {
    sorted := TRUE;
    size := size - 1;
    0.to (size - 1) do { i : INTEGER;
      (a.item(lower + i + 1) < a.item(lower + i)).if {
        t := a.item(lower + i + 1);
        a.put (a.item(lower + i)) to (lower + i + 1);
        a.put t to (lower + i);
        sorted := FALSE;
      };
    };
  }.do_while {!sorted};
);


function bubbleSort(A)
  local itemCount=#A
  local hasChanged
  repeat
    hasChanged = false
    itemCount=itemCount - 1
    for i = 1, itemCount do
      if A[i] > A[i + 1] then
        A[i], A[i + 1] = A[i + 1], A[i]
        hasChanged = true
      end
    end
  until hasChanged == false
end


#!/usr/bin/perl -w
use strict ;

# this function sorts the array in place
sub disjointSort {
   my ( $values , @indices ) = @_ ;

   @{$values}[ sort @indices ] = sort @{$values}[ @indices ] ;
}

my @values =  ( 7 , 6 , 5 , 4 , 3 , 2 , 1 , 0 ) ;
my @indices = ( 6 , 1 , 7 ) ;
disjointSort( \@values , @indices ) ;
print "[@values]\n" ;


with javascript_semantics
function disjoint_sort(sequence s, sequence idx)
    idx = unique(idx)
    integer l = length(idx)
    sequence copies = repeat(0, l)
    for i=1 to l do
        copies[i] = s[idx[i]]
    end for
    copies = sort(copies)
    for i=1 to l do
        s[idx[i]] = copies[i]
    end for
    return s
end function

?disjoint_sort({7,6,5,4,3,2,1,0},{7,2,8})


bsort(a) = if iseod(first a) then a else
              follow(bsort(allbutlast(b)),last(b)) fi
  where
   b = bubble(a);
   bubble(a) = smaller(max, next a)
       where
        max = first a fby larger(max, next a);
        larger(x,y) = if iseod(y) then y elseif x
       end;
   follow(x,y) = if xdone then y upon xdone else x fi
                   where
                      xdone = iseod x fby xdone or iseod x;
                   end;
   last(x) = (x asa iseod next x) fby eod;
   allbutlast(x) = if not iseod(next x) then x else eod fi;
  end


Module Bubble {
      function bubblesort {
                  dim a()
                  \\ []  is a stack object,  interpreter pass current stack pointer, and set a new stack for current stack
                  \\ array( stackobject ) get a stack object and return an array
                  a()=array([])
                  itemcount=len(a())
                   repeat {
                        haschange=false
                        if itemcount>1 then {
                              for index=0 to itemcount-2 {
                                  if a(index)>a(index+1) then swap a(index), a(index+1) : haschange=true
                              }
                        }
                       itemcount--
                   } until not haschange
                   =a()
      }
      \\ function can take parameters
      Print bubblesort(5,3,2,7,6,1)
      A=(2, 10, 17, 13, 20, 14, 3, 17, 16, 16)

      \\ !A copy values from array A to function stack
      B=bubblesort(!A)
      Print Len(A)=10
      Print B
      \\ Print array  in descending order
      k=each(b, -1, 1)
      While k {
            Print Array(k),
      }
      \\ sort two arrays in one
      Print BubbleSort(!A, !B)
      \\ We can use a stack object,  and values pop from object
      Z=Stack:=2, 10, 17, 13, 20, 14, 3, 17, 16, 16
      Print Len(Z)=10
      Def GetStack(x)=Stack(x)
      Z1=GetStack(BubbleSort(!Z))
      Print Type$(Z1)="mStiva"
      Print Z1
      Print Len(Z1)
      Print Len(Z)=0  ' now Z is empty
}
Bubble


(let (Values (7 6 5 4 3 2 1 0)  Indices (7 2 8))
   (mapc
      '((V I) (set (nth Values I) V))
      (sort (mapcar '((N) (get Values N)) Indices))
      (sort Indices) )
   Values )


% ===
% Problem description
% ===
% http://rosettacode.org/wiki/Sort_disjoint_sublist
%
% Given a list of values and a set of integer indices into that value list,
% the task is to sort the values at the given indices, while preserving the
% values at indices outside the set of those to be sorted.
%
% Make your example work with the following list of values and set of indices:
%
%        Values: [7, 6, 5, 4, 3, 2, 1, 0]
%
%        Indices: {6, 1, 7}
%
% Where the correct result would be:
%
%        [7, 0, 5, 4, 3, 2, 1, 6].
%
% In case of one-based indexing, rather than the zero-based indexing above,
% you would use the indices {7, 2, 8} instead.
%
% The indices are described as a set rather than a list but any collection-type
% of those indices without duplication may be used as long as the example is
% insensitive to the order of indices given.

% ===
% Notes
% ===
% For predicate descriptions, see https://www.swi-prolog.org/pldoc/man?section=preddesc
%
% Solution using only predicates marked "builtin".
%
% - sort/2 is a built-in predicate. When called as sort(A,B) then
%          it sorts A to B according to the "standard order of terms",
%          (for integers, this means ascending order). It does remove
%          duplicates.
% - msort/2 is the same as sort/2 but does not remove duplicates.
%
% Everything is a list as there is no "set" datatype in Prolog.

% ===
% Main predicate (the one that would be exported from a Module)
% sort_disjoint_sublist(+Values,+Indexes,?ValuesSorted)
% ===

sort_disjoint_sublist(Values,Indexes,ValuesSorted) :-
   sort(Indexes,IndexesSorted),
   insert_fresh_vars(0,IndexesSorted,Values,FreshVars,ValsToSort,ValuesFreshened),
   msort(ValsToSort,ValsSorted),  % this is the "sorting of values"
   % The next two lines could be left out with suitable naming,
   % but they make explicit what happens:
   FreshVars = ValsSorted,         % fresh variables are unified with sorted variables
   ValuesSorted = ValuesFreshened. % ValuesFreshend is automatically the sought output

% ===
% Helper predicate (would not be exported from a Module)
% ===

% insert_fresh_vars(+CurIdx,+[I|Is],+[V|Vs],-FreshVars,-ValsToSort,-ValsFreshy)
%
%   CurIdx:     Monotonically increasing index into the list of values by
%               which we iterate.
%   [I|Is]:     Sorted list of indexes of interest. The smallest (leftmost)
%               element is removed on every "index hit", leaving eventually
%               an empty list, which gives us the base case.
%   [V|Vs]:     The list of values of interest with the leftmost element the
%               element with index CurIdx, all elements with lower index
%               having been discarded. Leftmost element is popped off on
%               each call.
%   FreshVars:  Constructed as output. If there was an "index hit", the
%               fresh variable pushed on FreshVars is also pushed on Vars.
%   ValsToSort: Constructed as output. If there was an "index hit", the
%               leftmost value from [V|Vs] is pushed on.
%   ValsFreshy: Constructed as output. If there was an "index hit", a fresh
%               variable is pushed on. If there was no "index hit", the actual
%               value from [V|Vs] is pushed on instead.

insert_fresh_vars(CurIdx,[I|Is],[V|Vs],FreshVars,ValsToSort,[V|ValsFreshy]) :-
   CurIdx<I, % no index hit, CurIdx is still too small, iterate over value
   !,
   succ(CurIdx,NextIdx),
   insert_fresh_vars(NextIdx,[I|Is],Vs,FreshVars,ValsToSort,ValsFreshy).

insert_fresh_vars(CurIdx,[I|Is],[V|Vs],[Fresh|FreshVars],[V|ValsToSort],[Fresh|ValsFreshy]) :-
   CurIdx=I, % index hit, replace value by fresh variable
   !,
   succ(CurIdx,NextIdx),
   insert_fresh_vars(NextIdx,Is,Vs,FreshVars,ValsToSort,ValsFreshy).

insert_fresh_vars(_,[],V,[],[],V).


divert(-1)

define(`randSeed',141592653)
define(`setRand',
   `define(`randSeed',ifelse(eval($1<10000),1,`eval(20000-$1)',`$1'))')
define(`rand_t',`eval(randSeed^(randSeed>>13))')
define(`random',
   `define(`randSeed',eval((rand_t^(rand_t<<18))&0x7fffffff))randSeed')

define(`set',`define(`$1[$2]',`$3')')
define(`get',`defn(`$1[$2]')')
define(`new',`set($1,size,0)')
dnl  for the heap calculations, it's easier if origin is 0, so set value first
define(`append',
   `set($1,size,incr(get($1,size)))`'set($1,get($1,size),$2)')

dnl  swap(<name>,<j>,<name>[<j>],<k>)  using arg stack for the temporary
define(`swap',`set($1,$2,get($1,$4))`'set($1,$4,$3)')

define(`deck',
   `new($1)for(`x',1,$2,
         `append(`$1',eval(random%100))')')
define(`show',
   `for(`x',1,get($1,size),`get($1,x) ')')
define(`for',
   `ifelse($#,0,``$0'',
   `ifelse(eval($2<=$3),1,
   `pushdef(`$1',$2)$4`'popdef(`$1')$0(`$1',incr($2),$3,`$4')')')')

define(`bubbleonce',
   `for(`x',1,$2,
      `ifelse(eval(get($1,x)>get($1,incr(x))),1,
         `swap($1,x,get($1,x),incr(x))`'1')')0')
define(`bubbleupto',
   `ifelse(bubbleonce($1,$2),0,
      `',
      `bubbleupto($1,decr($2))')')
define(`bubblesort',
   `bubbleupto($1,decr(get($1,size)))')

divert
deck(`a',10)
show(`a')
bubblesort(`a')
show(`a')


function sublistsort($values, $indices) {
   $indices = $indices | sort
   $sub, $i = ($values[$indices] | sort), 0
   $indices | foreach { $values[$_] = $sub[$i++] }
   $values
}
$values = 7, 6, 5, 4, 3, 2, 1, 0
$indices = 6, 1, 7
"$(sublistsort $values $indices)"


Procedure Bubble_sort(Array idx(1), n, Array buf(1))
  Protected i, j
  SortArray(idx(),#PB_Sort_Ascending)
  For i=0 To n
    For j=i+1 To n
      If buf(idx(j)) < buf(idx(i))
        Swap buf(idx(j)), buf(idx(i))
      EndIf
    Next
  Next
EndProcedure

Procedure main()
  DataSection
    values: Data.i 7, 6, 5, 4, 3, 2, 1, 0
    indices:Data.i 6, 1, 7
  EndDataSection

  Dim values.i(7) :CopyMemory(?values, @values(), SizeOf(Integer)*8)
  Dim indices.i(2):CopyMemory(?indices,@indices(),SizeOf(Integer)*3)

  If OpenConsole()
    Protected i
    PrintN("Before sort:")
    For i=0 To ArraySize(values())
      Print(Str(values(i))+" ")
    Next

    PrintN(#CRLF$+#CRLF$+"After sort:")
    Bubble_sort(indices(), ArraySize(indices()), values())
    For i=0 To ArraySize(values())
      Print(Str(values(i))+" ")
    Next

    Print(#CRLF$+#CRLF$+"Press ENTER to exit")
    Input()
  EndIf
EndProcedure

main()


arr := Array([17,3,72,0,36,2,3,8,40,0]):
len := numelems(arr):
while(true) do
	change := false:
	len--;
	for i from 1 to len do
		if (arr[i] > arr[i+1]) then
			temp := arr[i]:
			arr[i] := arr[i+1]:
			arr[i+1] := temp:
			change := true:
		end if:
	end do:
	if (not change) then break end if:
end do:
arr;


bubbleSort[{w___, x_, y_, z___}] /; x > y := bubbleSort[{w, y, x, z}]
bubbleSort[sortedList_] := sortedList
bubbleSort[{10, 3, 7, 1, 4, 3, 8, 13, 9}]


>>> def sort_disjoint_sublist(data, indices):
	indices = sorted(indices)
	values  = sorted(data[i] for i in indices)
	for index, value in zip(indices, values):
		data[index] = value

>>> d = [7, 6, 5, 4, 3, 2, 1, 0]
>>> i = set([6, 1, 7])
>>> sort_disjoint_sublist(d, i)
>>> d
[7, 0, 5, 4, 3, 2, 1, 6]
>>> # Which could be more cryptically written as:
>>> def sort_disjoint_sublist(data, indices):
	for index, value in zip(sorted(indices), sorted(data[i] for i in indices)): data[index] = value

>>>


 values=c(7,6,5,4,3,2,1,0)
 indices=c(7,2,8)
 values[sort(indices)]=sort(values[indices])
 print(values)