Sorting algorithms/Bubble sort: Difference between revisions

Content added Content deleted
m (syntax highlighting fixup automation)
Line 40: Line 40:
{{trans|Python}}
{{trans|Python}}


<lang 11l>F bubble_sort(&seq)
<syntaxhighlight lang="11l">F bubble_sort(&seq)
V changed = 1B
V changed = 1B
L changed == 1B
L changed == 1B
Line 54: Line 54:
assert(testcase != testset)
assert(testcase != testset)
bubble_sort(&testcase)
bubble_sort(&testcase)
assert(testcase == testset)</lang>
assert(testcase == testset)</syntaxhighlight>


=={{header|360 Assembly}}==
=={{header|360 Assembly}}==
For maximum compatibility, this program uses only the basic instruction set.
For maximum compatibility, this program uses only the basic instruction set.
The program uses also HLASM structured macros (DO,ENDDO,IF,ELSE,ENDIF) for readability and two ASSIST/360 macros (XDECO,XPRNT) to keep the code as short as possible.
The program uses also HLASM structured macros (DO,ENDDO,IF,ELSE,ENDIF) for readability and two ASSIST/360 macros (XDECO,XPRNT) to keep the code as short as possible.
<lang 360 Assembly>* Bubble Sort 01/11/2014 & 23/06/2016
<syntaxhighlight lang="360 assembly">* Bubble Sort 01/11/2014 & 23/06/2016
BUBBLE CSECT
BUBBLE CSECT
USING BUBBLE,R13,R12 establish base registers
USING BUBBLE,R13,R12 establish base registers
Line 117: Line 117:
RN EQU 7 n-1
RN EQU 7 n-1
RM EQU 8 more
RM EQU 8 more
END BUBBLE</lang>
END BUBBLE</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 124: Line 124:
=={{header|6502 Assembly}}==
=={{header|6502 Assembly}}==
Code can be copied and pasted into Easy6502. Make sure you set the monitor to $1200 and check the check box to view it in action. Bubble Sort's infamous reputation is very well-deserved as this is going to take a few minutes to finish. This example takes a reverse identity table (where the 0th entry is $FF, the first is $FE, and so on) and sorts them in ascending order. Slowly. And the program might not run unless its tab is active in your browser. I'd play Game Boy to pass the time. ;)
Code can be copied and pasted into Easy6502. Make sure you set the monitor to $1200 and check the check box to view it in action. Bubble Sort's infamous reputation is very well-deserved as this is going to take a few minutes to finish. This example takes a reverse identity table (where the 0th entry is $FF, the first is $FE, and so on) and sorts them in ascending order. Slowly. And the program might not run unless its tab is active in your browser. I'd play Game Boy to pass the time. ;)
<lang 6502asm>define z_HL $00
<syntaxhighlight lang="6502asm">define z_HL $00
define z_L $00
define z_L $00
define z_H $01
define z_H $01
Line 178: Line 178:
jmp BUBBLESORT
jmp BUBBLESORT
DoneSorting:
DoneSorting:
rts</lang>
rts</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 201: Line 201:
=={{header|AArch64 Assembly}}==
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang="aarch64 assembly">
<lang AArch64 Assembly>
/* ARM assembly AARCH64 Raspberry PI 3B */
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program bubbleSort64.s */
/* program bubbleSort64.s */
Line 371: Line 371:
.include "../includeARM64.inc"
.include "../includeARM64.inc"


</syntaxhighlight>
</lang>
=={{header|ACL2}}==
=={{header|ACL2}}==
<lang Lisp>(defun bubble (xs)
<syntaxhighlight lang="lisp">(defun bubble (xs)
(if (endp (rest xs))
(if (endp (rest xs))
(mv nil xs)
(mv nil xs)
Line 398: Line 398:


(defun bsort (xs)
(defun bsort (xs)
(bsort-r xs (len xs)))</lang>
(bsort-r xs (len xs)))</syntaxhighlight>


=={{header|Action!}}==
=={{header|Action!}}==
<lang Action!>PROC PrintArray(INT ARRAY a INT size)
<syntaxhighlight lang="action!">PROC PrintArray(INT ARRAY a INT size)
INT i
INT i


Line 456: Line 456:
Test(c,8)
Test(c,8)
Test(d,12)
Test(d,12)
RETURN</lang>
RETURN</syntaxhighlight>
{{out}}
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Bubble_sort.png Screenshot from Atari 8-bit computer]
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Bubble_sort.png Screenshot from Atari 8-bit computer]
Line 482: Line 482:


=={{header|ActionScript}}==
=={{header|ActionScript}}==
<lang actionscript>public function bubbleSort(toSort:Array):Array
<syntaxhighlight lang="actionscript">public function bubbleSort(toSort:Array):Array
{
{
var changed:Boolean = false;
var changed:Boolean = false;
Line 504: Line 504:
return toSort;
return toSort;
}</lang>
}</syntaxhighlight>


=={{header|Ada}}==
=={{header|Ada}}==
{{works with|GCC|4.1.2}}
{{works with|GCC|4.1.2}}


<lang ada>generic
<syntaxhighlight lang="ada">generic
type Element is private;
type Element is private;
with function "=" (E1, E2 : Element) return Boolean is <>;
with function "=" (E1, E2 : Element) return Boolean is <>;
Line 552: Line 552:
end loop;
end loop;
New_Line;
New_Line;
end Main;</lang>
end Main;</syntaxhighlight>


=={{header|ALGOL 60}}==
=={{header|ALGOL 60}}==
{{works with|A60}}
{{works with|A60}}
<lang algol60>begin
<syntaxhighlight lang="algol60">begin
comment Sorting algorithms/Bubble sort - Algol 60;
comment Sorting algorithms/Bubble sort - Algol 60;
integer nA;
integer nA;
Line 603: Line 603:
writetable(1,nA)
writetable(1,nA)
end
end
end </lang>
end </syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 611: Line 611:


=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
<lang algol68>MODE DATA = INT;
<syntaxhighlight lang="algol68">MODE DATA = INT;
PROC swap = (REF[]DATA slice)VOID:
PROC swap = (REF[]DATA slice)VOID:
(
(
Line 642: Line 642:
sort(random);
sort(random);
printf(($"After: "10(g(3))l$,random))
printf(($"After: "10(g(3))l$,random))
)</lang>
)</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 650: Line 650:


=={{header|ALGOL W}}==
=={{header|ALGOL W}}==
<lang algolw>begin
<syntaxhighlight lang="algolw">begin
% As algol W does not allow overloading, we have to have type-specific %
% As algol W does not allow overloading, we have to have type-specific %
% sorting procedures - this bubble sorts an integer array %
% sorting procedures - this bubble sorts an integer array %
Line 709: Line 709:
writeData;
writeData;
end test
end test
end.</lang>
end.</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 720: Line 720:
In AppleScript, the time taken to set and check a "has changed" boolean repeatedly over the greater part of the sort generally matches or exceeds any time it may save. A more effective optimisation, since the greater value in any pair also takes part in the following comparison, is to keep the greater value in a variable and only fetch one value from the list for the next comparison.
In AppleScript, the time taken to set and check a "has changed" boolean repeatedly over the greater part of the sort generally matches or exceeds any time it may save. A more effective optimisation, since the greater value in any pair also takes part in the following comparison, is to keep the greater value in a variable and only fetch one value from the list for the next comparison.


<lang applescript>-- In-place bubble sort.
<syntaxhighlight lang="applescript">-- In-place bubble sort.
on bubbleSort(theList, l, r) -- Sort items l thru r of theList.
on bubbleSort(theList, l, r) -- Sort items l thru r of theList.
set listLen to (count theList)
set listLen to (count theList)
Line 757: Line 757:
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}
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.
sort(aList, 1, -1) -- Sort items 1 thru -1 of aList.
return aList</lang>
return aList</syntaxhighlight>


{{output}}
{{output}}
<lang applescript>{1, 2, 10, 11, 23, 27, 29, 29, 33, 37, 38, 45, 52, 55, 58, 61, 68, 70, 71, 73, 74, 77, 94, 95, 98}</lang>
<syntaxhighlight lang="applescript">{1, 2, 10, 11, 23, 27, 29, 29, 33, 37, 38, 45, 52, 55, 58, 61, 68, 70, 71, 73, 74, 77, 94, 95, 98}</syntaxhighlight>


=={{header|Arendelle}}==
=={{header|Arendelle}}==
Line 794: Line 794:
=={{header|ARM Assembly}}==
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
<lang ARM Assembly>


/* ARM assembly Raspberry PI */
/* ARM assembly Raspberry PI */
Line 952: Line 952:
/***************************************************/
/***************************************************/
.include "../affichage.inc"
.include "../affichage.inc"
</syntaxhighlight>
</lang>
=={{header|Arturo}}==
=={{header|Arturo}}==


<lang rebol>bubbleSort: function [items][
<syntaxhighlight lang="rebol">bubbleSort: function [items][
len: size items
len: size items
loop len [j][
loop len [j][
Line 971: Line 971:
]
]


print bubbleSort [3 1 2 8 5 7 9 4 6]</lang>
print bubbleSort [3 1 2 8 5 7 9 4 6]</syntaxhighlight>


{{out}}
{{out}}
Line 978: Line 978:


=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
<lang AutoHotkey>var =
<syntaxhighlight lang="autohotkey">var =
(
(
dog
dog
Line 1,012: Line 1,012:
sorted .= array%A_Index% . "`n"
sorted .= array%A_Index% . "`n"
Return sorted
Return sorted
}</lang>
}</syntaxhighlight>


=={{header|AWK}}==
=={{header|AWK}}==
Sort the standard input and print it to standard output.
Sort the standard input and print it to standard output.
<lang awk>{ # read every line into an array
<syntaxhighlight lang="awk">{ # read every line into an array
line[NR] = $0
line[NR] = $0
}
}
Line 1,035: Line 1,035:
print line[i]
print line[i]
}
}
}</lang>
}</syntaxhighlight>


GNU awk contains built in functions for sorting, but POSIX
GNU awk contains built in functions for sorting, but POSIX
Line 1,046: Line 1,046:
variables.
variables.


<lang awk>
<syntaxhighlight lang="awk">
# Test this example file from command line with:
# Test this example file from command line with:
#
#
Line 1,092: Line 1,092:
exit
exit
}
}
</syntaxhighlight>
</lang>


=={{header|bash}}==
=={{header|bash}}==
Line 1,098: Line 1,098:
I hope to see vastly improved versions of bubble_sort.
I hope to see vastly improved versions of bubble_sort.


<lang bash>
<syntaxhighlight lang="bash">
$ function bubble_sort() {
$ function bubble_sort() {
local a=("$@")
local a=("$@")
Line 1,139: Line 1,139:
-31 0 1 2 2 4 45 58 65 69 74 82 82 83 88 89 99 104 112 782
-31 0 1 2 2 4 45 58 65 69 74 82 82 83 88 89 99 104 112 782
$
$
</syntaxhighlight>
</lang>


=={{header|BASIC}}==
=={{header|BASIC}}==
Line 1,146: Line 1,146:
{{trans|Java}}
{{trans|Java}}
Assume numbers are in a DIM of size "size" called "nums".
Assume numbers are in a DIM of size "size" called "nums".
<lang qbasic>
<syntaxhighlight lang="qbasic">
DO
DO
changed = 0
changed = 0
Line 1,157: Line 1,157:
END IF
END IF
NEXT
NEXT
LOOP WHILE(NOT changed)</lang>
LOOP WHILE(NOT changed)</syntaxhighlight>


==={{header|Applesoft BASIC}}===
==={{header|Applesoft BASIC}}===
<lang basic>0 GOSUB 7 : IC = I%(0)
<syntaxhighlight lang="basic">0 GOSUB 7 : IC = I%(0)
1 FOR HC = -1 TO 0
1 FOR HC = -1 TO 0
2 LET IC = IC - 1
2 LET IC = IC - 1
Line 1,169: Line 1,169:
7 DIM I%(18000) : I%(0) = 50
7 DIM I%(18000) : I%(0) = 50
8 FOR I = 1 TO I%(0) : I%(I) = INT (RND(1) * 65535) - 32767 : NEXT
8 FOR I = 1 TO I%(0) : I%(I) = INT (RND(1) * 65535) - 32767 : NEXT
9 FOR I = 1 TO I%(0) : PRINT I%(I)" "; : NEXT I : PRINT : RETURN</lang>
9 FOR I = 1 TO I%(0) : PRINT I%(I)" "; : NEXT I : PRINT : RETURN</syntaxhighlight>


==={{header|Sinclair ZX81 BASIC}}===
==={{header|Sinclair ZX81 BASIC}}===
Works with the 1k RAM model. For simplicity, and to make it easy to animate the sort as it is going on, this implementation sorts a string of eight-bit unsigned integers which can be treated as character codes; it could easily be amended to sort an array of numbers or an array of strings, but the array would need to be dimensioned at the start.
Works with the 1k RAM model. For simplicity, and to make it easy to animate the sort as it is going on, this implementation sorts a string of eight-bit unsigned integers which can be treated as character codes; it could easily be amended to sort an array of numbers or an array of strings, but the array would need to be dimensioned at the start.
<lang basic> 10 LET S$="FIRE BURN AND CAULDRON BUBBLE"
<syntaxhighlight lang="basic"> 10 LET S$="FIRE BURN AND CAULDRON BUBBLE"
20 PRINT S$
20 PRINT S$
30 LET L=LEN S$-1
30 LET L=LEN S$-1
Line 1,186: Line 1,186:
120 NEXT I
120 NEXT I
130 LET L=L-1
130 LET L=L-1
140 IF C THEN GOTO 40</lang>
140 IF C THEN GOTO 40</syntaxhighlight>
{{out}}
{{out}}
<pre> AABBBBCDDEEFILLNNNORRRUUU</pre>
<pre> AABBBBCDDEEFILLNNNORRRUUU</pre>
Line 1,192: Line 1,192:
==={{header|BASIC256}}===
==={{header|BASIC256}}===
{{works with|BASIC256 }}
{{works with|BASIC256 }}
<lang basic256>
<syntaxhighlight lang="basic256">
Dim a(11): ordered=false
Dim a(11): ordered=false
print "Original set"
print "Original set"
Line 1,217: Line 1,217:
print a[n]+", ";
print a[n]+", ";
next n
next n
</syntaxhighlight>
</lang>
{{out}}(example)
{{out}}(example)
<pre>
<pre>
Line 1,228: Line 1,228:
==={{header|BBC BASIC}}===
==={{header|BBC BASIC}}===
The Bubble sort is very inefficient for 99% of cases. This routine uses a couple of 'tricks' to try and mitigate the inefficiency to a limited extent. Note that the array index is assumed to start at zero.
The Bubble sort is very inefficient for 99% of cases. This routine uses a couple of 'tricks' to try and mitigate the inefficiency to a limited extent. Note that the array index is assumed to start at zero.
<lang bbcbasic> DIM test(9)
<syntaxhighlight lang="bbcbasic"> DIM test(9)
test() = 4, 65, 2, -31, 0, 99, 2, 83, 782, 1
test() = 4, 65, 2, -31, 0, 99, 2, 83, 782, 1
PROCbubblesort(test(), 10)
PROCbubblesort(test(), 10)
Line 1,249: Line 1,249:
n% = l%
n% = l%
UNTIL l% = 0
UNTIL l% = 0
ENDPROC</lang>
ENDPROC</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,257: Line 1,257:


==={{header|Commodore BASIC}}===
==={{header|Commodore BASIC}}===
<syntaxhighlight lang="commodore">
<lang COMMODORE>
5 REM ===============================================
5 REM ===============================================
10 REM HTTP://ROSETTACODE.ORG/
10 REM HTTP://ROSETTACODE.ORG/
Line 1,305: Line 1,305:
910 DATA 15
910 DATA 15
920 DATA 64,34,25,12,22,11,90,13,59,47,19,89,10,17,31
920 DATA 64,34,25,12,22,11,90,13,59,47,19,89,10,17,31
</syntaxhighlight>
</lang>


==={{header|GW-BASIC}}===
==={{header|GW-BASIC}}===
<lang gwbasic>10 REM GENERATE A RANDOM BUNCH OF INTEGERS
<syntaxhighlight lang="gwbasic">10 REM GENERATE A RANDOM BUNCH OF INTEGERS
20 DIM ARR(20)
20 DIM ARR(20)
30 RANDOMIZE TIMER
30 RANDOMIZE TIMER
Line 1,331: Line 1,331:
1020 ARR(I+1) = TEMP
1020 ARR(I+1) = TEMP
1030 CHANGED = 1
1030 CHANGED = 1
1040 RETURN</lang>
1040 RETURN</syntaxhighlight>
{{out}}<pre>
{{out}}<pre>
20 59 42 9 5 91 6 64 21 28 65 96 20 66 66 70 91 98 63 31
20 59 42 9 5 91 6 64 21 28 65 96 20 66 66 70 91 98 63 31
Line 1,349: Line 1,349:


==={{header|IS-BASIC}}===
==={{header|IS-BASIC}}===
<lang IS-BASIC>100 PROGRAM "BubblSrt.bas"
<syntaxhighlight lang="is-basic">100 PROGRAM "BubblSrt.bas"
110 RANDOMIZE
110 RANDOMIZE
120 NUMERIC ARRAY(-5 TO 9)
120 NUMERIC ARRAY(-5 TO 9)
Line 1,374: Line 1,374:
330 NEXT
330 NEXT
340 LOOP WHILE CH
340 LOOP WHILE CH
350 END DEF</lang>
350 END DEF</syntaxhighlight>


==={{header|BaCon}}===
==={{header|BaCon}}===
Numeric example:
Numeric example:
<lang bacon>LOCAL t[] = { 5, 7, 1, 3, 10, 2, 9, 4, 8, 6 }
<syntaxhighlight lang="bacon">LOCAL t[] = { 5, 7, 1, 3, 10, 2, 9, 4, 8, 6 }
total = 10
total = 10
WHILE total > 1
WHILE total > 1
Line 1,386: Line 1,386:
DECR total
DECR total
WEND
WEND
PRINT COIL$(10, STR$(t[_-1]))</lang>
PRINT COIL$(10, STR$(t[_-1]))</syntaxhighlight>
{{out}}
{{out}}
<pre>1 2 3 4 5 6 7 8 9 10</pre>
<pre>1 2 3 4 5 6 7 8 9 10</pre>
String example:
String example:
<lang bacon>t$ = "Kiev Amsterdam Lima Moscow Warschau Vienna Paris Madrid Bonn Bern Rome"
<syntaxhighlight lang="bacon">t$ = "Kiev Amsterdam Lima Moscow Warschau Vienna Paris Madrid Bonn Bern Rome"
total = AMOUNT(t$)
total = AMOUNT(t$)
WHILE total > 1
WHILE total > 1
Line 1,398: Line 1,398:
DECR total
DECR total
WEND
WEND
PRINT t$</lang>
PRINT t$</syntaxhighlight>
{{out}}
{{out}}
<pre>Amsterdam Bern Bonn Kiev Lima Madrid Moscow Paris Rome Vienna Warschau</pre>
<pre>Amsterdam Bern Bonn Kiev Lima Madrid Moscow Paris Rome Vienna Warschau</pre>


=={{header|BCPL}}==
=={{header|BCPL}}==
<lang bcpl>get "libhdr"
<syntaxhighlight lang="bcpl">get "libhdr"


let bubblesort(v, length) be
let bubblesort(v, length) be
Line 1,425: Line 1,425:
for i=0 to 9 do writef("%N ", v!i)
for i=0 to 9 do writef("%N ", v!i)
wrch('*N')
wrch('*N')
$)</lang>
$)</syntaxhighlight>
{{out}}
{{out}}
<pre>1 2 3 4 5 6 7 8 9 10</pre>
<pre>1 2 3 4 5 6 7 8 9 10</pre>


=={{header|C}}==
=={{header|C}}==
<lang c>#include <stdio.h>
<syntaxhighlight lang="c">#include <stdio.h>


void bubble_sort (int *a, int n) {
void bubble_sort (int *a, int n) {
Line 1,459: Line 1,459:
return 0;
return 0;
}
}
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 1,468: Line 1,468:
=={{header|C sharp|C#}}==
=={{header|C sharp|C#}}==
{{works with|C sharp|C#|3.0+}}
{{works with|C sharp|C#|3.0+}}
<lang csharp>using System;
<syntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.Collections.Generic;


Line 1,511: Line 1,511:
}
}
}
}
}</lang>
}</syntaxhighlight>


=={{header|C++}}==
=={{header|C++}}==
Uses C++11. Compile with
Uses C++11. Compile with
g++ -std=c++11 bubble.cpp
g++ -std=c++11 bubble.cpp
<lang cpp>#include <algorithm>
<syntaxhighlight lang="cpp">#include <algorithm>
#include <iostream>
#include <iostream>
#include <iterator>
#include <iterator>
Line 1,539: Line 1,539:
copy(std::begin(a), std::end(a), std::ostream_iterator<int>(std::cout, " "));
copy(std::begin(a), std::end(a), std::ostream_iterator<int>(std::cout, " "));
std::cout << "\n";
std::cout << "\n";
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,548: Line 1,548:
Bubble sorts a Java ArrayList in place. Uses 'doseq' iteration construct with a short-circuit when a pass didn't produce any change, and within the pass, an atomic 'changed' variable that gets reset whenever a change occurs.
Bubble sorts a Java ArrayList in place. Uses 'doseq' iteration construct with a short-circuit when a pass didn't produce any change, and within the pass, an atomic 'changed' variable that gets reset whenever a change occurs.
<lang clojure>(ns bubblesort
<syntaxhighlight lang="clojure">(ns bubblesort
(:import java.util.ArrayList))
(:import java.util.ArrayList))
Line 1,574: Line 1,574:
arr)))
arr)))


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


Purely functional version working on Clojure sequences:
Purely functional version working on Clojure sequences:
<lang clojure>(defn- bubble-step
<syntaxhighlight lang="clojure">(defn- bubble-step
"was-changed: whether any elements prior to the current first element
"was-changed: whether any elements prior to the current first element
were swapped;
were swapped;
Line 1,603: Line 1,603:
(recur less? result)))))
(recur less? result)))))
(println (bubble-sort [10 9 8 7 6 5 4 3 2 1]))</lang>
(println (bubble-sort [10 9 8 7 6 5 4 3 2 1]))</syntaxhighlight>


=={{header|CLU}}==
=={{header|CLU}}==
<lang clu>% Bubble-sort an array in place.
<syntaxhighlight lang="clu">% Bubble-sort an array in place.
bubble_sort = proc [T: type] (a: array[T])
bubble_sort = proc [T: type] (a: array[T])
where T has lt: proctype (T,T) returns (bool)
where T has lt: proctype (T,T) returns (bool)
Line 1,641: Line 1,641:
bubble_sort[int](test)
bubble_sort[int](test)
stream$puts(po, "After: ") print_arr[int](test, 3, po)
stream$puts(po, "After: ") print_arr[int](test, 3, po)
end start_up</lang>
end start_up</syntaxhighlight>
{{out}}
{{out}}
<pre>Before: 7 -5 0 2 99 16 4 20 47 19
<pre>Before: 7 -5 0 2 99 16 4 20 47 19
Line 1,649: Line 1,649:
Only for lists of integers.
Only for lists of integers.


<lang cmake># bubble_sort(var [value1 value2...]) sorts a list of integers.
<syntaxhighlight lang="cmake"># bubble_sort(var [value1 value2...]) sorts a list of integers.
function(bubble_sort var)
function(bubble_sort var)
math(EXPR last "${ARGC} - 1") # Prepare to sort ARGV[1]..ARGV[last].
math(EXPR last "${ARGC} - 1") # Prepare to sort ARGV[1]..ARGV[last].
Line 1,674: Line 1,674:
endforeach(index)
endforeach(index)
set("${var}" "${answer}" PARENT_SCOPE)
set("${var}" "${answer}" PARENT_SCOPE)
endfunction(bubble_sort)</lang>
endfunction(bubble_sort)</syntaxhighlight>


<lang cmake>bubble_sort(result 33 11 44 22 66 55)
<syntaxhighlight lang="cmake">bubble_sort(result 33 11 44 22 66 55)
message(STATUS "${result}")</lang>
message(STATUS "${result}")</syntaxhighlight>


<pre>-- 11;22;33;44;55;66</pre>
<pre>-- 11;22;33;44;55;66</pre>
Line 1,684: Line 1,684:
This is a complete program that demonstrates the bubble sort algorithm in COBOL.
This is a complete program that demonstrates the bubble sort algorithm in COBOL.
<br/>This version is for COBOL-74 which does not have in-line performs, nor END-IF and related constructs.
<br/>This version is for COBOL-74 which does not have in-line performs, nor END-IF and related constructs.
<lang cobol>
<syntaxhighlight lang="cobol">
IDENTIFICATION DIVISION.
IDENTIFICATION DIVISION.
PROGRAM-ID. BUBBLESORT.
PROGRAM-ID. BUBBLESORT.
Line 1,830: Line 1,830:
F-999.
F-999.
EXIT.
EXIT.
</syntaxhighlight>
</lang>


A more modern version of COBOL.
A more modern version of COBOL.
<lang cobol>
<syntaxhighlight lang="cobol">
identification division.
identification division.
program-id. BUBBLSRT.
program-id. BUBBLSRT.
Line 1,888: Line 1,888:
end-perform
end-perform
.
.
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 1,895: Line 1,895:
=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
Bubble sort an sequence in-place, using the < operator for comparison if no comaprison function is provided
Bubble sort an sequence in-place, using the < operator for comparison if no comaprison function is provided
<lang lisp>(defun bubble-sort (sequence &optional (compare #'<))
<syntaxhighlight lang="lisp">(defun bubble-sort (sequence &optional (compare #'<))
"sort a sequence (array or list) with an optional comparison function (cl:< is the default)"
"sort a sequence (array or list) with an optional comparison function (cl:< is the default)"
(loop with sorted = nil until sorted do
(loop with sorted = nil until sorted do
Line 1,904: Line 1,904:
(rotatef (elt sequence a)
(rotatef (elt sequence a)
(elt sequence (1+ a)))
(elt sequence (1+ a)))
(setf sorted nil)))))</lang>
(setf sorted nil)))))</syntaxhighlight>


<lang lisp>(bubble-sort (list 5 4 3 2 1))</lang>
<syntaxhighlight lang="lisp">(bubble-sort (list 5 4 3 2 1))</syntaxhighlight>


<code>elt</code> has linear access time for lists, making the prior implementation of bubble-sort very expensive (although very clear, and straightforward to code. Here is an implementation that works efficiently for both vectors and lists. For lists it also has the nice property that the input list and the sorted list begin with the same <code>cons</code> cell.
<code>elt</code> has linear access time for lists, making the prior implementation of bubble-sort very expensive (although very clear, and straightforward to code. Here is an implementation that works efficiently for both vectors and lists. For lists it also has the nice property that the input list and the sorted list begin with the same <code>cons</code> cell.


<lang lisp>(defun bubble-sort-vector (vector predicate &aux (len (1- (length vector))))
<syntaxhighlight lang="lisp">(defun bubble-sort-vector (vector predicate &aux (len (1- (length vector))))
(do ((swapped t)) ((not swapped) vector)
(do ((swapped t)) ((not swapped) vector)
(setf swapped nil)
(setf swapped nil)
Line 1,929: Line 1,929:
(etypecase sequence
(etypecase sequence
(list (bubble-sort-list sequence predicate))
(list (bubble-sort-list sequence predicate))
(vector (bubble-sort-vector sequence predicate))))</lang>
(vector (bubble-sort-vector sequence predicate))))</syntaxhighlight>


=={{header|Cowgol}}==
=={{header|Cowgol}}==


<lang cowgol>include "cowgol.coh";
<syntaxhighlight lang="cowgol">include "cowgol.coh";


# Comparator interface, on the model of C, i.e:
# Comparator interface, on the model of C, i.e:
Line 1,987: Line 1,987:
i := i + 1;
i := i + 1;
end loop;
end loop;
print_nl();</lang>
print_nl();</syntaxhighlight>


{{out}}
{{out}}
Line 1,994: Line 1,994:


=={{header|D}}==
=={{header|D}}==
<lang d>import std.stdio, std.algorithm : swap;
<syntaxhighlight lang="d">import std.stdio, std.algorithm : swap;


T[] bubbleSort(T)(T[] data) pure nothrow
T[] bubbleSort(T)(T[] data) pure nothrow
Line 2,017: Line 2,017:
auto array = [28, 44, 46, 24, 19, 2, 17, 11, 25, 4];
auto array = [28, 44, 46, 24, 19, 2, 17, 11, 25, 4];
writeln(array.bubbleSort());
writeln(array.bubbleSort());
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>[2, 4, 11, 17, 19, 24, 25, 28, 44, 46]</pre>
<pre>[2, 4, 11, 17, 19, 24, 25, 28, 44, 46]</pre>
Line 2,047: Line 2,047:


Static array is an arbitrary-based array of fixed length
Static array is an arbitrary-based array of fixed length
<lang Delphi>program TestBubbleSort;
<syntaxhighlight lang="delphi">program TestBubbleSort;


{$APPTYPE CONSOLE}
{$APPTYPE CONSOLE}
Line 2,100: Line 2,100:
Writeln;
Writeln;
Readln;
Readln;
end.</lang>
end.</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,108: Line 2,108:


=={{header|Draco}}==
=={{header|Draco}}==
<lang draco>/* Bubble sort an array of integers */
<syntaxhighlight lang="draco">/* Bubble sort an array of integers */
proc nonrec bubblesort([*] int a) void:
proc nonrec bubblesort([*] int a) void:
bool sorted;
bool sorted;
Line 2,138: Line 2,138:
write("After sorting: ");
write("After sorting: ");
for i from 0 upto 9 do write(a[i]:5) od
for i from 0 upto 9 do write(a[i]:5) od
corp</lang>
corp</syntaxhighlight>
{{out}}
{{out}}
<pre>Before sorting: 9 -5 3 3 24 -16 3 -120 250 17
<pre>Before sorting: 9 -5 3 3 24 -16 3 -120 250 17
Line 2,145: Line 2,145:
=={{header|Dyalect}}==
=={{header|Dyalect}}==


<lang dyalect>func bubbleSort(list) {
<syntaxhighlight lang="dyalect">func bubbleSort(list) {
var done = false
var done = false
while !done {
while !done {
Line 2,162: Line 2,162:
var xs = [3,1,5,4,2,6]
var xs = [3,1,5,4,2,6]
bubbleSort(xs)
bubbleSort(xs)
print(xs)</lang>
print(xs)</syntaxhighlight>


{{out}}
{{out}}
Line 2,169: Line 2,169:


=={{header|E}}==
=={{header|E}}==
<lang e>def bubbleSort(target) {
<syntaxhighlight lang="e">def bubbleSort(target) {
__loop(fn {
__loop(fn {
var changed := false
var changed := false
Line 2,181: Line 2,181:
changed
changed
})
})
}</lang>
}</syntaxhighlight>


(Uses the primitive __loop directly because it happens to map to the termination test for this algorithm well.)
(Uses the primitive __loop directly because it happens to map to the termination test for this algorithm well.)


=={{header|EchoLisp}}==
=={{header|EchoLisp}}==
<lang scheme>
<syntaxhighlight lang="scheme">
;; sorts a vector of objects in place
;; sorts a vector of objects in place
;; proc is an user defined comparison procedure
;; proc is an user defined comparison procedure
Line 2,203: Line 2,203:
(bubble-sort V sort/length)
(bubble-sort V sort/length)
→ #(zen simon elvis albert antoinette)
→ #(zen simon elvis albert antoinette)
</syntaxhighlight>
</lang>


=={{header|EDSAC order code}}==
=={{header|EDSAC order code}}==
Line 2,212: Line 2,212:


To clarify the EDSAC program, an equivalent Pascal program is added as a comment.
To clarify the EDSAC program, an equivalent Pascal program is added as a comment.
<lang edsac>
<syntaxhighlight lang="edsac">
[Bubble sort demo for Rosetta Code website]
[Bubble sort demo for Rosetta Code website]
[EDSAC program. Initial Orders 2]
[EDSAC program. Initial Orders 2]
Line 2,364: Line 2,364:
E 14 Z [define entry point]
E 14 Z [define entry point]
P F [acc = 0 on entry]
P F [acc = 0 on entry]
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 2,384: Line 2,384:
This solution is presented in two classes. The first is a simple application that creates a set, an instance of <code lang="eiffel">MY_SORTED_SET</code>, and adds elements to the set in unsorted order. It iterates across the set printing the elements, then it sorts the set, and reprints the elements.
This solution is presented in two classes. The first is a simple application that creates a set, an instance of <code lang="eiffel">MY_SORTED_SET</code>, and adds elements to the set in unsorted order. It iterates across the set printing the elements, then it sorts the set, and reprints the elements.


<lang eiffel>class
<syntaxhighlight lang="eiffel">class
APPLICATION
APPLICATION
create
create
Line 2,413: Line 2,413:
my_set: MY_SORTED_SET [INTEGER]
my_set: MY_SORTED_SET [INTEGER]
-- Set to be sorted
-- Set to be sorted
end</lang>
end</syntaxhighlight>


The second class is <code lang="eiffel">MY_SORTED_SET</code>.
The second class is <code lang="eiffel">MY_SORTED_SET</code>.


<lang eiffel>class
<syntaxhighlight lang="eiffel">class
MY_SORTED_SET [G -> COMPARABLE]
MY_SORTED_SET [G -> COMPARABLE]
inherit
inherit
Line 2,452: Line 2,452:
end
end
end
end
end</lang>
end</syntaxhighlight>


This class inherits from the Eiffel library class <code lang="eiffel">TWO_WAY_SORTED_SET</code>, which implements sets whose elements are comparable. Therefore, the set can be ordered and in fact is kept so under normal circumstances.
This class inherits from the Eiffel library class <code lang="eiffel">TWO_WAY_SORTED_SET</code>, which implements sets whose elements are comparable. Therefore, the set can be ordered and in fact is kept so under normal circumstances.
Line 2,473: Line 2,473:
{{trans|C#}}
{{trans|C#}}
ELENA 5.0 :
ELENA 5.0 :
<lang elena>import system'routines;
<syntaxhighlight lang="elena">import system'routines;
import extensions;
import extensions;
Line 2,506: Line 2,506:
var list := new int[]{3, 7, 3, 2, 1, -4, 10, 12, 4};
var list := new int[]{3, 7, 3, 2, 1, -4, 10, 12, 4};
console.printLine(list.bubbleSort().asEnumerable())
console.printLine(list.bubbleSort().asEnumerable())
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,513: Line 2,513:


=={{header|Elixir}}==
=={{header|Elixir}}==
<lang elixir>defmodule Sort do
<syntaxhighlight lang="elixir">defmodule Sort do
def bsort(list) when is_list(list) do
def bsort(list) when is_list(list) do
t = bsort_iter(list)
t = bsort_iter(list)
Line 2,523: Line 2,523:
def bsort_iter([x, y | t]), do: [x | bsort_iter([y | t])]
def bsort_iter([x, y | t]), do: [x | bsort_iter([y | t])]
def bsort_iter(list), do: list
def bsort_iter(list), do: list
end</lang>
end</syntaxhighlight>


=={{header|Erlang}}==
=={{header|Erlang}}==
sort/3 copied from Stackoverflow.
sort/3 copied from Stackoverflow.
<syntaxhighlight lang="erlang">
<lang Erlang>
-module( bubble_sort ).
-module( bubble_sort ).


Line 2,544: Line 2,544:
sort( [X, Y | T], Acc, _Done ) when X > Y -> sort( [X | T], [Y | Acc], false );
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 ).
sort( [X | T], Acc, Done ) -> sort( T, [X | Acc], Done ).
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 2,552: Line 2,552:


=={{header|ERRE}}==
=={{header|ERRE}}==
<syntaxhighlight lang="erre">
<lang ERRE>
PROGRAM BUBBLE_SORT
PROGRAM BUBBLE_SORT


Line 2,584: Line 2,584:
PRINT
PRINT
END PROGRAM
END PROGRAM
</syntaxhighlight>
</lang>


=={{header|Euphoria}}==
=={{header|Euphoria}}==
<lang euphoria>function bubble_sort(sequence s)
<syntaxhighlight lang="euphoria">function bubble_sort(sequence s)
object tmp
object tmp
integer changed
integer changed
Line 2,613: Line 2,613:
pretty_print(1,s,{2})
pretty_print(1,s,{2})
puts(1,"\nAfter: ")
puts(1,"\nAfter: ")
pretty_print(1,bubble_sort(s),{2})</lang>
pretty_print(1,bubble_sort(s),{2})</syntaxhighlight>


{{out}}
{{out}}
Line 2,650: Line 2,650:


=={{header|Ezhil}}==
=={{header|Ezhil}}==
<syntaxhighlight lang="ezhil">
<lang Ezhil>


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


</syntaxhighlight>
</lang>


=={{header|F Sharp|F#}}==
=={{header|F Sharp|F#}}==
<lang fsharp>let BubbleSort (lst : list<int>) =
<syntaxhighlight lang="fsharp">let BubbleSort (lst : list<int>) =
let rec sort accum rev lst =
let rec sort accum rev lst =
match lst, rev with
match lst, rev with
Line 2,729: Line 2,729:
| head::tail, _ -> sort (head::accum) rev tail
| head::tail, _ -> sort (head::accum) rev tail
sort [] true lst
sort [] true lst
</syntaxhighlight>
</lang>


=={{header|Factor}}==
=={{header|Factor}}==
<lang factor>USING: fry kernel locals math math.order sequences
<syntaxhighlight lang="factor">USING: fry kernel locals math math.order sequences
sequences.private ;
sequences.private ;
IN: rosetta.bubble
IN: rosetta.bubble
Line 2,754: Line 2,754:


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


It is possible to pass your own comparison operator to <code>sort!</code>, so you can f.e. sort your sequence backwards with passing <code>[ >=< ]</code> into it.
It is possible to pass your own comparison operator to <code>sort!</code>, so you can f.e. sort your sequence backwards with passing <code>[ >=< ]</code> into it.


<lang factor>10 [ 10000 random ] replicate
<syntaxhighlight lang="factor">10 [ 10000 random ] replicate
[ "Before: " write . ]
[ "Before: " write . ]
[ "Natural: " write [ natural-sort! ] keep . ]
[ "Natural: " write [ natural-sort! ] keep . ]
[ "Reverse: " write [ [ >=< ] sort! ] keep . ] tri</lang>
[ "Reverse: " write [ [ >=< ] sort! ] keep . ] tri</syntaxhighlight>


Before: { 3707 5045 4661 1489 3140 7195 8844 6506 6322 3199 }
Before: { 3707 5045 4661 1489 3140 7195 8844 6506 6322 3199 }
Line 2,770: Line 2,770:
This is not a complete implementation of bubblesort: it doesn't keep a boolean flag whether to stop, so it goes on printing each stage of the sorting process ad infinitum.
This is not a complete implementation of bubblesort: it doesn't keep a boolean flag whether to stop, so it goes on printing each stage of the sorting process ad infinitum.


<lang fish>v Sorts the (pre-loaded) stack
<syntaxhighlight lang="fish">v Sorts the (pre-loaded) stack
with bubblesort.
with bubblesort.
v <
v <
Line 2,777: Line 2,777:
>~{ao ^
>~{ao ^
>~}l &{ v
>~}l &{ v
o","{n:&-1^?=0:&<</lang>
o","{n:&-1^?=0:&<</syntaxhighlight>


=={{header|Forth}}==
=={{header|Forth}}==
Sorts the 'cnt' cells stored at 'addr' using the test stored in the deferred word 'bubble-test'. Uses forth local variables for clarity.
Sorts the 'cnt' cells stored at 'addr' using the test stored in the deferred word 'bubble-test'. Uses forth local variables for clarity.


<lang forth>defer bubble-test
<syntaxhighlight lang="forth">defer bubble-test
' > is bubble-test
' > is bubble-test


Line 2,790: Line 2,790:
i 2@ bubble-test if i 2@ swap i 2! then
i 2@ bubble-test if i 2@ swap i 2! then
cell +loop
cell +loop
loop ;</lang>
loop ;</syntaxhighlight>


This is the same algorithm done without the local variables:
This is the same algorithm done without the local variables:


<lang forth>: bubble ( addr cnt -- )
<syntaxhighlight lang="forth">: bubble ( addr cnt -- )
dup 1 do
dup 1 do
2dup i - cells bounds do
2dup i - cells bounds do
i 2@ bubble-test if i 2@ swap i 2! then
i 2@ bubble-test if i 2@ swap i 2! then
cell +loop
cell +loop
loop ;</lang>
loop ;</syntaxhighlight>


Version with ''O(n)'' best case:
Version with ''O(n)'' best case:
<lang forth>: bubble ( addr len -- )
<syntaxhighlight lang="forth">: bubble ( addr len -- )
begin
begin
1- 2dup true -rot ( sorted addr len-1 )
1- 2dup true -rot ( sorted addr len-1 )
Line 2,811: Line 2,811:
then
then
cell +loop ( sorted )
cell +loop ( sorted )
until 2drop ;</lang>
until 2drop ;</syntaxhighlight>


Test any version with this:
Test any version with this:
Line 2,827: Line 2,827:


=={{header|Fortran}}==
=={{header|Fortran}}==
<lang fortran>SUBROUTINE Bubble_Sort(a)
<syntaxhighlight lang="fortran">SUBROUTINE Bubble_Sort(a)
REAL, INTENT(in out), DIMENSION(:) :: a
REAL, INTENT(in out), DIMENSION(:) :: a
REAL :: temp
REAL :: temp
Line 2,845: Line 2,845:
IF (.NOT. swapped) EXIT
IF (.NOT. swapped) EXIT
END DO
END DO
END SUBROUTINE Bubble_Sort</lang>
END SUBROUTINE Bubble_Sort</syntaxhighlight>


=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
Per task pseudo code:
Per task pseudo code:
<lang FreeBASIC>' version 21-10-2016
<syntaxhighlight lang="freebasic">' version 21-10-2016
' compile with: fbc -s console
' compile with: fbc -s console
' for boundry checks on array's compile with: fbc -s console -exx
' for boundry checks on array's compile with: fbc -s console -exx
Line 2,895: Line 2,895:
Print : Print "hit any key to end program"
Print : Print "hit any key to end program"
Sleep
Sleep
End</lang>
End</syntaxhighlight>
{{out}}
{{out}}
<pre>unsort -7 3 -4 -6 4 -1 -2 2 7 0 5 1 -3 -5 6
<pre>unsort -7 3 -4 -6 4 -1 -2 2 7 0 5 1 -3 -5 6
Line 2,901: Line 2,901:


=={{header|g-fu}}==
=={{header|g-fu}}==
<lang g-fu>
<syntaxhighlight lang="g-fu">
(fun bubbles (vs)
(fun bubbles (vs)
(let done? F n (len vs))
(let done? F n (len vs))
Line 2,917: Line 2,917:
---
---
(1 2 3)
(1 2 3)
</syntaxhighlight>
</lang>


=={{header|Gambas}}==
=={{header|Gambas}}==
'''[https://gambas-playground.proko.eu/?gist=ba84832d633cb92bbe6c2f54704819c3 Click this link to run this code]'''
'''[https://gambas-playground.proko.eu/?gist=ba84832d633cb92bbe6c2f54704819c3 Click this link to run this code]'''
<lang gambas>Public Sub Main()
<syntaxhighlight lang="gambas">Public Sub Main()
Dim byToSort As Byte[] = [249, 28, 111, 36, 171, 98, 29, 448, 44, 147, 154, 46, 102, 183, 24,
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]
120, 19, 123, 2, 17, 226, 11, 211, 25, 191, 205, 77]
Line 2,952: Line 2,952:
Print
Print


End</lang>
End</syntaxhighlight>
Output:
Output:
<pre>
<pre>
Line 2,982: Line 2,982:
=={{header|Go}}==
=={{header|Go}}==
Per task pseudocode:
Per task pseudocode:
<lang go>package main
<syntaxhighlight lang="go">package main


import "fmt"
import "fmt"
Line 3,007: Line 3,007:
}
}
}
}
}</lang>
}</syntaxhighlight>


More generic version that can sort anything that implements <code>sort.Interface</code>:
More generic version that can sort anything that implements <code>sort.Interface</code>:
<lang go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 3,038: Line 3,038:
}
}
}
}
}</lang>
}</syntaxhighlight>


=={{header|Groovy}}==
=={{header|Groovy}}==
Solution:
Solution:
<lang groovy>def makeSwap = { a, i, j = i+1 -> print "."; a[[i,j]] = a[[j,i]] }
<syntaxhighlight lang="groovy">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 checkSwap = { a, i, j = i+1 -> [(a[i] > a[j])].find { it }.each { makeSwap(a, i, j) } }
Line 3,050: Line 3,050:
while (swapped) { swapped = (1..<list.size()).any { checkSwap(list, it-1) } }
while (swapped) { swapped = (1..<list.size()).any { checkSwap(list, it-1) } }
list
list
}</lang>
}</syntaxhighlight>


Test Program:
Test Program:
<lang groovy>println bubbleSort([23,76,99,58,97,57,35,89,51,38,95,92,24,46,31,24,14,12,57,78,4])
<syntaxhighlight lang="groovy">println bubbleSort([23,76,99,58,97,57,35,89,51,38,95,92,24,46,31,24,14,12,57,78,4])
println bubbleSort([88,18,31,44,4,0,8,81,14,78,20,76,84,33,73,75,82,5,62,70,12,7,1])</lang>
println bubbleSort([88,18,31,44,4,0,8,81,14,78,20,76,84,33,73,75,82,5,62,70,12,7,1])</syntaxhighlight>


{{out}}
{{out}}
Line 3,062: Line 3,062:
=={{header|Haskell}}==
=={{header|Haskell}}==
This version checks for changes in a separate step for simplicity, because Haskell has no variables to track them with.
This version checks for changes in a separate step for simplicity, because Haskell has no variables to track them with.
<lang haskell>bsort :: Ord a => [a] -> [a]
<syntaxhighlight lang="haskell">bsort :: Ord a => [a] -> [a]
bsort s = case _bsort s of
bsort s = case _bsort s of
t | t == s -> t
t | t == s -> t
Line 3,068: Line 3,068:
where _bsort (x:x2:xs) | x > x2 = x2:(_bsort (x:xs))
where _bsort (x:x2:xs) | x > x2 = x2:(_bsort (x:xs))
| otherwise = x:(_bsort (x2:xs))
| otherwise = x:(_bsort (x2:xs))
_bsort s = s</lang>
_bsort s = s</syntaxhighlight>


This version uses the polymorphic <tt>Maybe</tt> type to designate unchanged lists. (The type signature of <tt>_bsort</tt> is now <tt>Ord a => [a] -> Maybe [a]</tt>.) It is slightly faster than the previous one.
This version uses the polymorphic <tt>Maybe</tt> type to designate unchanged lists. (The type signature of <tt>_bsort</tt> is now <tt>Ord a => [a] -> Maybe [a]</tt>.) It is slightly faster than the previous one.


<lang haskell>import Data.Maybe (fromMaybe)
<syntaxhighlight lang="haskell">import Data.Maybe (fromMaybe)
import Control.Monad
import Control.Monad


Line 3,080: Line 3,080:
then Just $ x2 : fromMaybe (x:xs) (_bsort $ x:xs)
then Just $ x2 : fromMaybe (x:xs) (_bsort $ x:xs)
else liftM (x:) $ _bsort (x2:xs)
else liftM (x:) $ _bsort (x2:xs)
_bsort _ = Nothing</lang>
_bsort _ = Nothing</syntaxhighlight>


This version is based on the above, but avoids sorting the whole list each time. To implement this without a counter and retain using pattern matching, inner sorting is reversed, and then the result is reversed back. Sorting is based on a predicate, e.g., (<) or (>).
This version is based on the above, but avoids sorting the whole list each time. To implement this without a counter and retain using pattern matching, inner sorting is reversed, and then the result is reversed back. Sorting is based on a predicate, e.g., (<) or (>).


<lang haskell>import Data.Maybe (fromMaybe)
<syntaxhighlight lang="haskell">import Data.Maybe (fromMaybe)
import Control.Monad
import Control.Monad


Line 3,099: Line 3,099:


bsort :: Ord a => [a] -> [a]
bsort :: Ord a => [a] -> [a]
bsort = bubbleSortBy (<)</lang>
bsort = bubbleSortBy (<)</syntaxhighlight>


=={{header|Haxe}}==
=={{header|Haxe}}==
<lang haxe>class BubbleSort {
<syntaxhighlight lang="haxe">class BubbleSort {
@:generic
@:generic
public static function sort<T>(arr:Array<T>) {
public static function sort<T>(arr:Array<T>) {
Line 3,140: Line 3,140:
Sys.println('Sorted Strings: ' + stringArray);
Sys.println('Sorted Strings: ' + stringArray);
}
}
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 3,153: Line 3,153:


=={{header|HicEst}}==
=={{header|HicEst}}==
<lang fortran>SUBROUTINE Bubble_Sort(a)
<syntaxhighlight lang="fortran">SUBROUTINE Bubble_Sort(a)
REAL :: a(1)
REAL :: a(1)
Line 3,168: Line 3,168:
IF (swapped == 0) RETURN
IF (swapped == 0) RETURN
ENDDO
ENDDO
END</lang>
END</syntaxhighlight>


=={{header|Icon}} and {{header|Unicon}}==
=={{header|Icon}} and {{header|Unicon}}==
Icon/Unicon implementation of a bubble sort
Icon/Unicon implementation of a bubble sort
<lang Icon>procedure main() #: demonstrate various ways to sort a list and string
<syntaxhighlight lang="icon">procedure main() #: demonstrate various ways to sort a list and string
demosort(bubblesort,[3, 14, 1, 5, 9, 2, 6, 3],"qwerty")
demosort(bubblesort,[3, 14, 1, 5, 9, 2, 6, 3],"qwerty")
end
end
Line 3,187: Line 3,187:
X[i-1] :=: X[swapped := i]
X[i-1] :=: X[swapped := i]
return X
return X
end</lang>
end</syntaxhighlight>


{{out}}
{{out}}
Line 3,207: Line 3,207:
* 'demosort' can apply different sorting procedures and operators to lists and strings to show how this works. The routines 'displaysort' and 'writex' are helpers.
* 'demosort' can apply different sorting procedures and operators to lists and strings to show how this works. The routines 'displaysort' and 'writex' are helpers.


<lang icon>invocable all # for op
<syntaxhighlight lang="icon">invocable all # for op


procedure sortop(op,X) #: select how to sort
procedure sortop(op,X) #: select how to sort
Line 3,265: Line 3,265:
write()
write()
return
return
end</lang>
end</syntaxhighlight>


=={{header|Io}}==
=={{header|Io}}==
<syntaxhighlight lang="io">
<lang Io>
List do(
List do(
bubblesort := method(
bubblesort := method(
Line 3,284: Line 3,284:
)
)
)
)
</syntaxhighlight>
</lang>


=={{header|J}}==
=={{header|J}}==
{{eff note|J|/:~ list}}
{{eff note|J|/:~ list}}
<lang j>bubbleSort=: (([ (<. , >.) {.@]) , }.@])/^:_</lang>
<syntaxhighlight lang="j">bubbleSort=: (([ (<. , >.) {.@]) , }.@])/^:_</syntaxhighlight>


Test program:
Test program:


<lang j> ?. 10 $ 10
<syntaxhighlight lang="j"> ?. 10 $ 10
4 6 8 6 5 8 6 6 6 9
4 6 8 6 5 8 6 6 6 9
bubbleSort ?. 10 $ 10
bubbleSort ?. 10 $ 10
4 5 6 6 6 6 6 8 8 9</lang>
4 5 6 6 6 6 6 8 8 9</syntaxhighlight>


For the most part, bubble sort works against J's strengths. However, once a single pass has been implemented as a list operation, <code>^:_</code> tells J to repeat this until the result stops changing.
For the most part, bubble sort works against J's strengths. However, once a single pass has been implemented as a list operation, <code>^:_</code> tells J to repeat this until the result stops changing.


=={{header|Janet}}==
=={{header|Janet}}==
<lang janet>
<syntaxhighlight lang="janet">
(defn bubble-sort!
(defn bubble-sort!
[arr]
[arr]
Line 3,326: Line 3,326:


)
)
</syntaxhighlight>
</lang>


=={{header|Java}}==
=={{header|Java}}==
Bubble sorting (ascending) an array of any <tt>Comparable</tt> type:
Bubble sorting (ascending) an array of any <tt>Comparable</tt> type:
<lang java>public static <E extends Comparable<? super E>> void bubbleSort(E[] comparable) {
<syntaxhighlight lang="java">public static <E extends Comparable<? super E>> void bubbleSort(E[] comparable) {
boolean changed = false;
boolean changed = false;
do {
do {
Line 3,343: Line 3,343:
}
}
} while (changed);
} while (changed);
}</lang>
}</syntaxhighlight>


For descending, simply switch the direction of comparison:
For descending, simply switch the direction of comparison:
<lang java>if (comparable[a].compareTo(comparable[b]) < 0){
<syntaxhighlight lang="java">if (comparable[a].compareTo(comparable[b]) < 0){
//same swap code as before
//same swap code as before
}</lang>
}</syntaxhighlight>


=={{header|JavaScript}}==
=={{header|JavaScript}}==
<lang javascript>Array.prototype.bubblesort = function() {
<syntaxhighlight lang="javascript">Array.prototype.bubblesort = function() {
var done = false;
var done = false;
while (!done) {
while (!done) {
Line 3,363: Line 3,363:
}
}
return this;
return this;
}</lang>
}</syntaxhighlight>


{{works with|SEE|3.0}}
{{works with|SEE|3.0}}
{{works with|OSSP js|1.6.20070208}}
{{works with|OSSP js|1.6.20070208}}
<lang javascript>Array.prototype.bubblesort = function() {
<syntaxhighlight lang="javascript">Array.prototype.bubblesort = function() {
var done = false;
var done = false;
while (! done) {
while (! done) {
Line 3,381: Line 3,381:
}
}
return this;
return this;
}</lang>
}</syntaxhighlight>


Example:
Example:
<lang javascript>var my_arr = ["G", "F", "C", "A", "B", "E", "D"];
<syntaxhighlight lang="javascript">var my_arr = ["G", "F", "C", "A", "B", "E", "D"];
my_arr.bubblesort();
my_arr.bubblesort();
print(my_arr);</lang>
print(my_arr);</syntaxhighlight>


{{out}}
{{out}}
Line 3,394: Line 3,394:


webpage version (for the rest of us):
webpage version (for the rest of us):
<lang javascript><script>
<syntaxhighlight lang="javascript"><script>
Array.prototype.bubblesort = function() {
Array.prototype.bubblesort = function() {
var done = false;
var done = false;
Line 3,416: Line 3,416:
}
}
document.write(output);
document.write(output);
</script></lang>
</script></syntaxhighlight>


=={{header|jq}}==
=={{header|jq}}==
<lang jq>def bubble_sort:
<syntaxhighlight lang="jq">def bubble_sort:
def swap(i;j): .[i] as $x | .[i]=.[j] | .[j]=$x;
def swap(i;j): .[i] as $x | .[i]=.[j] | .[j]=$x;


Line 3,432: Line 3,432:
else .
else .
end )
end )
end ) | .[1] ;</lang>
end ) | .[1] ;</syntaxhighlight>
'''Example''':
'''Example''':
<lang jq>(
<syntaxhighlight lang="jq">(
[3,2,1],
[3,2,1],
[1,2,3],
[1,2,3],
["G", "F", "C", "A", "B", "E", "D"]
["G", "F", "C", "A", "B", "E", "D"]
) | bubble_sort</lang>
) | bubble_sort</syntaxhighlight>
{{Out}}
{{Out}}
<lang sh>$ jq -c -n -f Bubble_sort.jq
<syntaxhighlight lang="sh">$ jq -c -n -f Bubble_sort.jq
[1,2,3]
[1,2,3]
[1,2,3]
[1,2,3]
["A","B","C","D","E","F","G"]</lang>
["A","B","C","D","E","F","G"]</syntaxhighlight>


=={{header|Julia}}==
=={{header|Julia}}==
{{works with|Julia|0.6}}
{{works with|Julia|0.6}}


<lang julia>function bubblesort!(arr::AbstractVector)
<syntaxhighlight lang="julia">function bubblesort!(arr::AbstractVector)
for _ in 2:length(arr), j in 1:length(arr)-1
for _ in 2:length(arr), j in 1:length(arr)-1
if arr[j] > arr[j+1]
if arr[j] > arr[j+1]
Line 3,458: Line 3,458:


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


{{out}}
{{out}}
Line 3,467: Line 3,467:
{{trans|Java}}
{{trans|Java}}


<lang scala>import java.util.Comparator
<syntaxhighlight lang="scala">import java.util.Comparator


fun <T> bubbleSort(a: Array<T>, c: Comparator<T>) {
fun <T> bubbleSort(a: Array<T>, c: Comparator<T>) {
Line 3,482: Line 3,482:
}
}
} while (changed)
} while (changed)
}</lang>
}</syntaxhighlight>


=={{header|Lambdatalk}}==
=={{header|Lambdatalk}}==
<lang scheme>
<syntaxhighlight lang="scheme">
{def bubblesort
{def bubblesort
{def bubblesort.swap!
{def bubblesort.swap!
Line 3,510: Line 3,510:
{bubblesort {A.new 0 3 86 20 27 67 31 16 37 42 8 47 7 84 5 29}}
{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]
-> [0,3,5,7,8,16,20,27,29,31,37,42,47,67,84,86]
</syntaxhighlight>
</lang>


=={{header|Liberty BASIC}}==
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">
<lang lb>
itemCount = 20
itemCount = 20
dim item(itemCount)
dim item(itemCount)
Line 3,542: Line 3,542:
next i
next i
end
end
</syntaxhighlight>
</lang>


=={{header|Lisaac}}==
=={{header|Lisaac}}==
<lang Lisaac>Section Header
<syntaxhighlight lang="lisaac">Section Header


+ name := BUBBLE_SORT;
+ name := BUBBLE_SORT;
Line 3,587: Line 3,587:
};
};
}.do_while {!sorted};
}.do_while {!sorted};
);</lang>
);</syntaxhighlight>


=={{header|Lua}}==
=={{header|Lua}}==


<syntaxhighlight lang="lua">
<lang Lua>
function bubbleSort(A)
function bubbleSort(A)
local itemCount=#A
local itemCount=#A
Line 3,606: Line 3,606:
until hasChanged == false
until hasChanged == false
end
end
</syntaxhighlight>
</lang>


Example:
Example:
<lang lua>
<syntaxhighlight lang="lua">
list = { 5, 6, 1, 2, 9, 14, 2, 15, 6, 7, 8, 97 }
list = { 5, 6, 1, 2, 9, 14, 2, 15, 6, 7, 8, 97 }
bubbleSort(list)
bubbleSort(list)
Line 3,615: Line 3,615:
print(j)
print(j)
end
end
</syntaxhighlight>
</lang>


=={{header|Lucid}}==
=={{header|Lucid}}==
[http://i.csc.uvic.ca/home/hei/lup/06.html]
[http://i.csc.uvic.ca/home/hei/lup/06.html]
<lang lucid>bsort(a) = if iseod(first a) then a else
<syntaxhighlight lang="lucid">bsort(a) = if iseod(first a) then a else
follow(bsort(allbutlast(b)),last(b)) fi
follow(bsort(allbutlast(b)),last(b)) fi
where
where
Line 3,634: Line 3,634:
last(x) = (x asa iseod next x) fby eod;
last(x) = (x asa iseod next x) fby eod;
allbutlast(x) = if not iseod(next x) then x else eod fi;
allbutlast(x) = if not iseod(next x) then x else eod fi;
end</lang>
end</syntaxhighlight>


=={{header|M2000 Interpreter}}==
=={{header|M2000 Interpreter}}==
Line 3,642: Line 3,642:




<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module Bubble {
Module Bubble {
function bubblesort {
function bubblesort {
Line 3,687: Line 3,687:
}
}
Bubble
Bubble
</syntaxhighlight>
</lang>


=={{header|M4}}==
=={{header|M4}}==
<lang M4>divert(-1)
<syntaxhighlight lang="m4">divert(-1)


define(`randSeed',141592653)
define(`randSeed',141592653)
Line 3,734: Line 3,734:
show(`a')
show(`a')
bubblesort(`a')
bubblesort(`a')
show(`a')</lang>
show(`a')</syntaxhighlight>


{{out}}
{{out}}
Line 3,742: Line 3,742:


=={{header|Maple}}==
=={{header|Maple}}==
<lang>arr := Array([17,3,72,0,36,2,3,8,40,0]):
<syntaxhighlight lang="text">arr := Array([17,3,72,0,36,2,3,8,40,0]):
len := numelems(arr):
len := numelems(arr):
while(true) do
while(true) do
Line 3,757: Line 3,757:
if (not change) then break end if:
if (not change) then break end if:
end do:
end do:
arr;</lang>
arr;</syntaxhighlight>
{{Out|Output}}
{{Out|Output}}
<pre>[0,0,2,3,3,8,17,36,40,72]</pre>
<pre>[0,0,2,3,3,8,17,36,40,72]</pre>
Line 3,763: Line 3,763:
=={{header|Mathematica}}/{{header|Wolfram Language}}==
=={{header|Mathematica}}/{{header|Wolfram Language}}==
===Using pattern matching===
===Using pattern matching===
<lang Mathematica>bubbleSort[{w___, x_, y_, z___}] /; x > y := bubbleSort[{w, y, x, z}]
<syntaxhighlight lang="mathematica">bubbleSort[{w___, x_, y_, z___}] /; x > y := bubbleSort[{w, y, x, z}]
bubbleSort[sortedList_] := sortedList
bubbleSort[sortedList_] := sortedList
bubbleSort[{10, 3, 7, 1, 4, 3, 8, 13, 9}]</lang>
bubbleSort[{10, 3, 7, 1, 4, 3, 8, 13, 9}]</syntaxhighlight>
{{out}}
{{out}}
<pre>{1, 3, 3, 4, 7, 8, 9, 10, 13}</pre>
<pre>{1, 3, 3, 4, 7, 8, 9, 10, 13}</pre>
===Classic version===
===Classic version===
<lang Mathematica>ClearAll[BubbleSort]
<syntaxhighlight lang="mathematica">ClearAll[BubbleSort]
BubbleSort[in_List] := Module[{x = in, l = Length[in], swapped},
BubbleSort[in_List] := Module[{x = in, l = Length[in], swapped},
swapped = True;
swapped = True;
Line 3,785: Line 3,785:
x
x
]
]
BubbleSort[{1, 12, 3, 7, 2, 8, 4, 7, 6}]</lang>
BubbleSort[{1, 12, 3, 7, 2, 8, 4, 7, 6}]</syntaxhighlight>
{{out}}
{{out}}
<pre>{1, 2, 3, 4, 6, 7, 7, 8, 12}</pre>
<pre>{1, 2, 3, 4, 6, 7, 7, 8, 12}</pre>
Line 3,791: Line 3,791:
=={{header|MATLAB}}==
=={{header|MATLAB}}==


<lang MATLAB>function list = bubbleSort(list)
<syntaxhighlight lang="matlab">function list = bubbleSort(list)


hasChanged = true;
hasChanged = true;
Line 3,810: Line 3,810:
end %for
end %for
end %while
end %while
end %bubbleSort</lang>
end %bubbleSort</syntaxhighlight>


{{out}}
{{out}}
Line 3,820: Line 3,820:


=={{header|MAXScript}}==
=={{header|MAXScript}}==
<lang maxscript>fn bubbleSort arr =
<syntaxhighlight lang="maxscript">fn bubbleSort arr =
(
(
while true do
while true do
Line 3,836: Line 3,836:
)
)
arr
arr
)</lang>
)</syntaxhighlight>
-- Usage
-- Usage
<lang maxscript>myArr = #(9, 8, 7, 6, 5, 4, 3, 2, 1)
<syntaxhighlight lang="maxscript">myArr = #(9, 8, 7, 6, 5, 4, 3, 2, 1)
myArr = bubbleSort myArr</lang>
myArr = bubbleSort myArr</syntaxhighlight>


=={{header|MMIX}}==
=={{header|MMIX}}==
<lang mmix>Ja IS $127
<syntaxhighlight lang="mmix">Ja IS $127


LOC Data_Segment
LOC Data_Segment
Line 3,921: Line 3,921:
JMP 2B % loop
JMP 2B % loop
1H XOR $255,$255,$255
1H XOR $255,$255,$255
TRAP 0,Halt,0 % exit(0)</lang>
TRAP 0,Halt,0 % exit(0)</syntaxhighlight>


=={{header|Modula-2}}==
=={{header|Modula-2}}==
<lang modula2>PROCEDURE BubbleSort(VAR a: ARRAY OF INTEGER);
<syntaxhighlight lang="modula2">PROCEDURE BubbleSort(VAR a: ARRAY OF INTEGER);
VAR
VAR
changed: BOOLEAN;
changed: BOOLEAN;
Line 3,942: Line 3,942:
END
END
UNTIL NOT changed
UNTIL NOT changed
END BubbleSort;</lang>
END BubbleSort;</syntaxhighlight>


=={{header|Modula-3}}==
=={{header|Modula-3}}==


<lang modula3>MODULE Bubble;
<syntaxhighlight lang="modula3">MODULE Bubble;


PROCEDURE Sort(VAR a: ARRAY OF INTEGER) =
PROCEDURE Sort(VAR a: ARRAY OF INTEGER) =
Line 3,965: Line 3,965:
END;
END;
END Sort;
END Sort;
END Bubble.</lang>
END Bubble.</syntaxhighlight>


=={{header|N/t/roff}}==
=={{header|N/t/roff}}==
Line 3,977: Line 3,977:
{{works with|GROFF (GNU Troff)|1.22.2}}
{{works with|GROFF (GNU Troff)|1.22.2}}


<lang N/t/roff>
<syntaxhighlight lang="n/t/roff">
.ig
.ig
Bubble sort algorithm in Troff
Bubble sort algorithm in Troff
Line 4,048: Line 4,048:
.nr Ai 0 1
.nr Ai 0 1
.while \n(Ai<\n(Ac \n[A\n+[Ai]]
.while \n(Ai<\n(Ac \n[A\n+[Ai]]
</syntaxhighlight>
</lang>


===Output===
===Output===
Line 4,057: Line 4,057:
=={{header|Nanoquery}}==
=={{header|Nanoquery}}==
{{trans|Python}}
{{trans|Python}}
<lang Nanoquery>def bubble_sort(seq)
<syntaxhighlight lang="nanoquery">def bubble_sort(seq)
changed = true
changed = true


Line 4,084: Line 4,084:
testset = bubble_sort(testset)
testset = bubble_sort(testset)
println testset
println testset
end</lang>
end</syntaxhighlight>


{{out}}
{{out}}
Line 4,093: Line 4,093:
=={{header|Nemerle}}==
=={{header|Nemerle}}==
===Functional===
===Functional===
<lang Nemerle>using System;
<syntaxhighlight lang="nemerle">using System;
using System.Console;
using System.Console;


Line 4,135: Line 4,135:
WriteLine(Bubblesort(several));
WriteLine(Bubblesort(several));
}
}
}</lang>
}</syntaxhighlight>
===Imperative===
===Imperative===
{{trans|C#}}
{{trans|C#}}
We use an array for this version so that we can update in place. We could use a C# style list (as in the C# example), but that seemed too easy to confuse with a Nemerle style list.
We use an array for this version so that we can update in place. We could use a C# style list (as in the C# example), but that seemed too easy to confuse with a Nemerle style list.
<lang Nemerle>using System;
<syntaxhighlight lang="nemerle">using System;
using System.Console;
using System.Console;


Line 4,171: Line 4,171:
Write($"$i ");
Write($"$i ");
}
}
}</lang>
}</syntaxhighlight>


=={{header|NetRexx}}==
=={{header|NetRexx}}==
<lang NetRexx>/* NetRexx */
<syntaxhighlight lang="netrexx">/* NetRexx */
options replace format comments java crossref savelog symbols binary
options replace format comments java crossref savelog symbols binary


Line 4,210: Line 4,210:


return list
return list
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre style="height: 20ex; overflow: scroll;">
<pre style="height: 20ex; overflow: scroll;">
Line 4,235: Line 4,235:
===Translation of Pseudocode===
===Translation of Pseudocode===
This version is a direct implementation of this task's pseudocode.
This version is a direct implementation of this task's pseudocode.
<lang NetRexx>/* NetRexx */
<syntaxhighlight lang="netrexx">/* NetRexx */
options replace format comments java crossref savelog symbols binary
options replace format comments java crossref savelog symbols binary


Line 4,281: Line 4,281:
method isFalse public constant binary returns boolean
method isFalse public constant binary returns boolean
return \isTrue
return \isTrue
</syntaxhighlight>
</lang>


=={{header|Nim}}==
=={{header|Nim}}==
<lang nim>proc bubbleSort[T](a: var openarray[T]) =
<syntaxhighlight lang="nim">proc bubbleSort[T](a: var openarray[T]) =
var t = true
var t = true
for n in countdown(a.len-2, 0):
for n in countdown(a.len-2, 0):
Line 4,296: Line 4,296:
var a = @[4, 65, 2, -31, 0, 99, 2, 83, 782]
var a = @[4, 65, 2, -31, 0, 99, 2, 83, 782]
bubbleSort a
bubbleSort a
echo a</lang>
echo a</syntaxhighlight>
{{out}}
{{out}}
<pre>@[-31, 0, 2, 2, 4, 65, 83, 99, 782]</pre>
<pre>@[-31, 0, 2, 2, 4, 65, 83, 99, 782]</pre>
Line 4,302: Line 4,302:
=={{header|Objeck}}==
=={{header|Objeck}}==
{{trans|C}}
{{trans|C}}
<lang objeck>
<syntaxhighlight lang="objeck">
function : Swap(p : Int[]) ~ Nil {
function : Swap(p : Int[]) ~ Nil {
t := p[0];
t := p[0];
Line 4,322: Line 4,322:
while (sorted = false);
while (sorted = false);
}
}
</syntaxhighlight>
</lang>


=={{header|Objective-C}}==
=={{header|Objective-C}}==
<lang objc>- (NSArray *) bubbleSort:(NSMutableArray *)unsorted {
<syntaxhighlight lang="objc">- (NSArray *) bubbleSort:(NSMutableArray *)unsorted {
BOOL done = false;
BOOL done = false;
Line 4,340: Line 4,340:
return unsorted;
return unsorted;
}
}
</syntaxhighlight>
</lang>


=={{header|OCaml}}==
=={{header|OCaml}}==
Line 4,346: Line 4,346:


This version checks for changes in a separate step for simplicity.
This version checks for changes in a separate step for simplicity.
<lang ocaml>let rec bsort s =
<syntaxhighlight lang="ocaml">let rec bsort s =
let rec _bsort = function
let rec _bsort = function
| x :: x2 :: xs when x > x2 ->
| x :: x2 :: xs when x > x2 ->
Line 4,356: Line 4,356:
let t = _bsort s in
let t = _bsort s in
if t = s then t
if t = s then t
else bsort t</lang>
else bsort t</syntaxhighlight>


This version uses the polymorphic <tt>option</tt> type to designate unchanged lists. (The type signature of <tt>_bsort</tt> is now <tt>'a list -> 'a list option</tt>.) It is slightly faster than the previous one.
This version uses the polymorphic <tt>option</tt> type to designate unchanged lists. (The type signature of <tt>_bsort</tt> is now <tt>'a list -> 'a list option</tt>.) It is slightly faster than the previous one.
<lang ocaml>let rec bsort s =
<syntaxhighlight lang="ocaml">let rec bsort s =
let rec _bsort = function
let rec _bsort = function
| x :: x2 :: xs when x > x2 -> begin
| x :: x2 :: xs when x > x2 -> begin
Line 4,375: Line 4,375:
match _bsort s with
match _bsort s with
| None -> s
| None -> s
| Some s2 -> bsort s2</lang>
| Some s2 -> bsort s2</syntaxhighlight>


=={{header|Octave}}==
=={{header|Octave}}==
<lang octave>function s = bubblesort(v)
<syntaxhighlight lang="octave">function s = bubblesort(v)
itemCount = length(v);
itemCount = length(v);
do
do
Line 4,391: Line 4,391:
until(hasChanged == false)
until(hasChanged == false)
s = v;
s = v;
endfunction</lang>
endfunction</syntaxhighlight>


<lang octave>v = [9,8,7,3,1,100];
<syntaxhighlight lang="octave">v = [9,8,7,3,1,100];
disp(bubblesort(v));</lang>
disp(bubblesort(v));</syntaxhighlight>


=={{header|Ol}}==
=={{header|Ol}}==
<lang scheme>
<syntaxhighlight lang="scheme">
(define (bubble-sort x ??)
(define (bubble-sort x ??)
(define (sort-step l)
(define (sort-step l)
Line 4,416: Line 4,416:
(print
(print
(bubble-sort (iota 100) <))
(bubble-sort (iota 100) <))
</syntaxhighlight>
</lang>


{{Out}}
{{Out}}
Line 4,429: Line 4,429:
{{trans|NetRexx}}
{{trans|NetRexx}}
This version exploits the &quot;Collection Classes&quot; and some other features of the language that are only available in Open Object Rexx.
This version exploits the &quot;Collection Classes&quot; and some other features of the language that are only available in Open Object Rexx.
<lang ooRexx>/* Rexx */
<syntaxhighlight lang="oorexx">/* Rexx */
Do
Do
placesList = sampleData()
placesList = sampleData()
Line 4,491: Line 4,491:
Exit
Exit


</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre style="height: 20ex; overflow: scroll;">
<pre style="height: 20ex; overflow: scroll;">
Line 4,515: Line 4,515:
===Translation of Pseudocode===
===Translation of Pseudocode===
This version is a direct implementation of this task's pseudocode.
This version is a direct implementation of this task's pseudocode.
<lang ooRexx>/* Rexx */
<syntaxhighlight lang="oorexx">/* Rexx */
Do
Do
placesList = sampleData()
placesList = sampleData()
Line 4,587: Line 4,587:
isFalse: procedure
isFalse: procedure
return \isTrue()
return \isTrue()
</syntaxhighlight>
</lang>


===Classic [[REXX|Rexx]] Implementation===
===Classic [[REXX|Rexx]] Implementation===
A more &quot;traditional&quot; implementation of version 1 using only Rexx primitive constructs. This version has been tested with the ''Open Object Rexx'' and ''Regina'' Rexx interpreters and could equally have been exhibited as a [[#REXX|Rexx]] solution.
A more &quot;traditional&quot; implementation of version 1 using only Rexx primitive constructs. This version has been tested with the ''Open Object Rexx'' and ''Regina'' Rexx interpreters and could equally have been exhibited as a [[#REXX|Rexx]] solution.
<lang ooRexx>/* Rexx */
<syntaxhighlight lang="oorexx">/* Rexx */
Do
Do
placesList. = ''
placesList. = ''
Line 4,652: Line 4,652:
End
End
Exit
Exit
</syntaxhighlight>
</lang>


=={{header|Oz}}==
=={{header|Oz}}==
In-place sorting of mutable arrays:
In-place sorting of mutable arrays:
<lang oz>declare
<syntaxhighlight lang="oz">declare
proc {BubbleSort Arr}
proc {BubbleSort Arr}
proc {Swap I J}
proc {Swap I J}
Line 4,678: Line 4,678:
in
in
{BubbleSort Arr}
{BubbleSort Arr}
{Inspect Arr}</lang>
{Inspect Arr}</syntaxhighlight>


Purely-functional sorting of immutable lists:
Purely-functional sorting of immutable lists:
<lang oz>declare
<syntaxhighlight lang="oz">declare
local
local
fun {Loop Xs Changed ?IsSorted}
fun {Loop Xs Changed ?IsSorted}
Line 4,705: Line 4,705:
end
end
in
in
{Show {BubbleSort [3 1 4 1 5 9 2 6 5]}}</lang>
{Show {BubbleSort [3 1 4 1 5 9 2 6 5]}}</syntaxhighlight>


=={{header|PARI/GP}}==
=={{header|PARI/GP}}==
<lang parigp>bubbleSort(v)={
<syntaxhighlight lang="parigp">bubbleSort(v)={
for(i=1,#v-1,
for(i=1,#v-1,
for(j=i+1,#v,
for(j=i+1,#v,
Line 4,719: Line 4,719:
);
);
v
v
};</lang>
};</syntaxhighlight>


=={{header|Pascal}}==
=={{header|Pascal}}==
<lang pascal>procedure bubble_sort(var list: array of real);
<syntaxhighlight lang="pascal">procedure bubble_sort(var list: array of real);
var
var
i, j, n: integer;
i, j, n: integer;
Line 4,736: Line 4,736:
list[j + 1] := t;
list[j + 1] := t;
end;
end;
end;</lang>
end;</syntaxhighlight>


Usage:<lang pascal>var
Usage:<syntaxhighlight lang="pascal">var
list: array[0 .. 9] of real;
list: array[0 .. 9] of real;
// ...
// ...
bubble_sort(list);</lang>
bubble_sort(list);</syntaxhighlight>


=={{header|Perl}}==
=={{header|Perl}}==
<lang perl># Sorts an array in place
<syntaxhighlight lang="perl"># Sorts an array in place
sub bubble_sort {
sub bubble_sort {
for my $i (0 .. $#_){
for my $i (0 .. $#_){
Line 4,751: Line 4,751:
}
}
}
}
}</lang>
}</syntaxhighlight>


Usage:
Usage:


<lang perl>my @a = (39, 25, 30, 28, 36, 72, 98, 25, 43, 38);
<syntaxhighlight lang="perl">my @a = (39, 25, 30, 28, 36, 72, 98, 25, 43, 38);
bubble_sort(@a);</lang>
bubble_sort(@a);</syntaxhighlight>


=={{header|Phix}}==
=={{header|Phix}}==
<!--<lang Phix>(phixonline)-->
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
Line 4,786: Line 4,786:
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"After: "</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"After: "</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">bubble_sort</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">bubble_sort</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
<!--</lang>-->
<!--</syntaxhighlight>-->
{{out}}
{{out}}
<pre>
<pre>
Line 4,795: Line 4,795:
=={{header|PHP}}==
=={{header|PHP}}==


<lang php>function bubbleSort(array $array){
<syntaxhighlight lang="php">function bubbleSort(array $array){
foreach($array as $i => &$val){
foreach($array as $i => &$val){
foreach($array as $k => &$val2){
foreach($array as $k => &$val2){
Line 4,807: Line 4,807:
}
}
return $array;
return $array;
}</lang>
}</syntaxhighlight>


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
<lang PicoLisp>(de bubbleSort (Lst)
<syntaxhighlight lang="picolisp">(de bubbleSort (Lst)
(use Chg
(use Chg
(loop
(loop
Line 4,818: Line 4,818:
(xchg L (cdr L))
(xchg L (cdr L))
(on Chg) ) )
(on Chg) ) )
(NIL Chg Lst) ) ) )</lang>
(NIL Chg Lst) ) ) )</syntaxhighlight>


=={{header|PL/I}}==
=={{header|PL/I}}==
<lang pli>/* A primitive bubble sort */
<syntaxhighlight lang="pli">/* A primitive bubble sort */
bubble_sort: procedure (A);
bubble_sort: procedure (A);
declare A(*) fixed binary;
declare A(*) fixed binary;
Line 4,836: Line 4,836:
end;
end;
end;
end;
end bubble_sort;</lang>
end bubble_sort;</syntaxhighlight>


=={{header|Pop11}}==
=={{header|Pop11}}==
<lang pop11>define bubble_sort(v);
<syntaxhighlight lang="pop11">define bubble_sort(v);
lvars n=length(v), done=false, i;
lvars n=length(v), done=false, i;
while not(done) do
while not(done) do
Line 4,857: Line 4,857:
vars ar = { 10 8 6 4 2 1 3 5 7 9};
vars ar = { 10 8 6 4 2 1 3 5 7 9};
bubble_sort(ar);
bubble_sort(ar);
ar =></lang>
ar =></syntaxhighlight>


=={{header|PostScript}}==
=={{header|PostScript}}==
<syntaxhighlight lang="postscript">
<lang PostScript>
/bubblesort{
/bubblesort{
/x exch def
/x exch def
Line 4,882: Line 4,882:
x pstack
x pstack
}def
}def
</syntaxhighlight>
</lang>


=={{header|PowerShell}}==
=={{header|PowerShell}}==
<lang powershell>function bubblesort ($a) {
<syntaxhighlight lang="powershell">function bubblesort ($a) {
$l = $a.Length
$l = $a.Length
$hasChanged = $true
$hasChanged = $true
Line 4,898: Line 4,898:
}
}
}
}
}</lang>
}</syntaxhighlight>


=={{header|Prolog}}==
=={{header|Prolog}}==
Line 4,904: Line 4,904:
to the bubble sort algorithm. Some of these are easier and shorter to code and work as well if not better. Having said that,
to the bubble sort algorithm. Some of these are easier and shorter to code and work as well if not better. Having said that,
it's difficult to think of a reason to code the bubble sort these days except as an example of inefficiency.
it's difficult to think of a reason to code the bubble sort these days except as an example of inefficiency.
<lang prolog>%___________________________________________________________________________
<syntaxhighlight lang="prolog">%___________________________________________________________________________
% Bubble sort
% Bubble sort


Line 4,923: Line 4,923:
writef(' input=%w\n', [In]),
writef(' input=%w\n', [In]),
bubblesort(In, R),
bubblesort(In, R),
writef('-> %w\n', [R]).</lang>
writef('-> %w\n', [R]).</syntaxhighlight>
for example:
for example:
<pre>?- test.
<pre>?- test.
Line 4,936: Line 4,936:
Should be ISO (but tested only with GNU Prolog).
Should be ISO (but tested only with GNU Prolog).
Note: doesn't constuct list for each swap, only for each pass.
Note: doesn't constuct list for each swap, only for each pass.
<lang prolog>:- initialization(main).
<syntaxhighlight lang="prolog">:- initialization(main).




Line 4,957: Line 4,957:
test([8,9,1,3,4,2,6,5,4]).
test([8,9,1,3,4,2,6,5,4]).


main :- test(T), bubble_sort(T,_), halt.</lang>
main :- test(T), bubble_sort(T,_), halt.</syntaxhighlight>
{{Out}}
{{Out}}
<pre>[8,9,1,3,4,2,6,5,4]
<pre>[8,9,1,3,4,2,6,5,4]
Line 4,966: Line 4,966:


=={{header|PureBasic}}==
=={{header|PureBasic}}==
<lang PureBasic>Procedure bubbleSort(Array a(1))
<syntaxhighlight lang="purebasic">Procedure bubbleSort(Array a(1))
Protected i, itemCount, hasChanged
Protected i, itemCount, hasChanged
Line 4,980: Line 4,980:
Next
Next
Until hasChanged = #False
Until hasChanged = #False
EndProcedure</lang>
EndProcedure</syntaxhighlight>


=={{header|Python}}==
=={{header|Python}}==
<lang python>def bubble_sort(seq):
<syntaxhighlight lang="python">def bubble_sort(seq):
"""Inefficiently sort the mutable sequence (list) in place.
"""Inefficiently sort the mutable sequence (list) in place.
seq MUST BE A MUTABLE SEQUENCE.
seq MUST BE A MUTABLE SEQUENCE.
Line 5,008: Line 5,008:
assert testcase != testset # we've shuffled it
assert testcase != testset # we've shuffled it
bubble_sort(testcase)
bubble_sort(testcase)
assert testcase == testset # we've unshuffled it back into a copy</lang>
assert testcase == testset # we've unshuffled it back into a copy</syntaxhighlight>


=={{header|Quackery}}==
=={{header|Quackery}}==


<lang Quackery> [ stack ] is sorted ( --> s )
<syntaxhighlight lang="quackery"> [ stack ] is sorted ( --> s )
[ rot tuck over peek
[ rot tuck over peek
Line 5,034: Line 5,034:
[ 10 random join ]
[ 10 random join ]
say "Before: " dup echo cr
say "Before: " dup echo cr
say "After: " bubble echo</lang>
say "After: " bubble echo</syntaxhighlight>


{{out}}
{{out}}
Line 5,043: Line 5,043:


=={{header|Qi}}==
=={{header|Qi}}==
<lang Qi>(define bubble-shot
<syntaxhighlight lang="qi">(define bubble-shot
[A] -> [A]
[A] -> [A]
[A B|R] -> [B|(bubble-shot [A|R])] where (> A B)
[A B|R] -> [B|(bubble-shot [A|R])] where (> A B)
Line 5,052: Line 5,052:


(bubble-sort [6 8 5 9 3 2 2 1 4 7])
(bubble-sort [6 8 5 9 3 2 2 1 4 7])
</syntaxhighlight>
</lang>


=={{header|R}}==
=={{header|R}}==
The previously solution missed out on a cool R trick for swapping items and had no check for lists of length 1. As R is 1-indexed, we have aimed to be as faithful as we can to the given pseudo-code.
The previously solution missed out on a cool R trick for swapping items and had no check for lists of length 1. As R is 1-indexed, we have aimed to be as faithful as we can to the given pseudo-code.
<lang rsplus>bubbleSort <- function(items)
<syntaxhighlight lang="rsplus">bubbleSort <- function(items)
{
{
repeat
repeat
Line 5,078: Line 5,078:
ints <- c(1, 10, 2, 5, -1, 5, -19, 4, 23, 0)
ints <- c(1, 10, 2, 5, -1, 5, -19, 4, 23, 0)
numerics <- c(1, -3.2, 5.2, 10.8, -5.7, 7.3, 3.5, 0, -4.1, -9.5)
numerics <- c(1, -3.2, 5.2, 10.8, -5.7, 7.3, 3.5, 0, -4.1, -9.5)
strings <- c("We", "hold", "these", "truths", "to", "be", "self-evident", "that", "all", "men", "are", "created", "equal")</lang>
strings <- c("We", "hold", "these", "truths", "to", "be", "self-evident", "that", "all", "men", "are", "created", "equal")</syntaxhighlight>


{{out}}
{{out}}
Line 5,090: Line 5,090:


=={{header|Ra}}==
=={{header|Ra}}==
<syntaxhighlight lang="ra">
<lang Ra>
class BubbleSort
class BubbleSort
**Sort a list with the Bubble Sort algorithm**
**Sort a list with the Bubble Sort algorithm**
Line 5,122: Line 5,122:
list[i + 1] := temp
list[i + 1] := temp
changed := true
changed := true
</syntaxhighlight>
</lang>


=={{header|Racket}}==
=={{header|Racket}}==
Line 5,128: Line 5,128:
This bubble sort sorts the elelement in the vector v with regard to <?.
This bubble sort sorts the elelement in the vector v with regard to <?.


<lang racket>
<syntaxhighlight lang="racket">
#lang racket
#lang racket


Line 5,145: Line 5,145:
(when again? (loop (- max 1) #f)))
(when again? (loop (- max 1) #f)))
v)
v)
</syntaxhighlight>
</lang>


Example: Sorting a vector of length 10 with random entries.
Example: Sorting a vector of length 10 with random entries.
<lang racket>
<syntaxhighlight lang="racket">
(bubble-sort < (for/vector ([_ 10]) (random 20)))
(bubble-sort < (for/vector ([_ 10]) (random 20)))
</syntaxhighlight>
</lang>


=={{header|Raku}}==
=={{header|Raku}}==
Line 5,156: Line 5,156:
{{works with|Rakudo|#24 "Seoul"}}
{{works with|Rakudo|#24 "Seoul"}}


<lang perl6>sub bubble_sort (@a) {
<syntaxhighlight lang="raku" line>sub bubble_sort (@a) {
for ^@a -> $i {
for ^@a -> $i {
for $i ^..^ @a -> $j {
for $i ^..^ @a -> $j {
Line 5,162: Line 5,162:
}
}
}
}
}</lang>
}</syntaxhighlight>


=={{header|REALbasic}}==
=={{header|REALbasic}}==
Line 5,168: Line 5,168:
Sorts an array of Integers
Sorts an array of Integers


<syntaxhighlight lang="vb">
<lang vb>
Dim sortable() As Integer = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
Dim sortable() As Integer = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
sortable.Shuffle() ' sortable is now randomized
sortable.Shuffle() ' sortable is now randomized
Line 5,188: Line 5,188:
Loop Until Not swapped
Loop Until Not swapped
'sortable is now sorted
'sortable is now sorted
</syntaxhighlight>
</lang>


=={{header|REXX}}==
=={{header|REXX}}==
===version 0, alpha-numeric vertical list===
===version 0, alpha-numeric vertical list===
This REXX version sorts (using a bubble sort) and displays an array &nbsp; (of alpha-numeric items) &nbsp; in a vertical list.
This REXX version sorts (using a bubble sort) and displays an array &nbsp; (of alpha-numeric items) &nbsp; in a vertical list.
<lang rexx>/*REXX program sorts an array (of any kind of items) using the bubble─sort algorithm.*/
<syntaxhighlight lang="rexx">/*REXX program sorts an array (of any kind of items) using the bubble─sort algorithm.*/
call gen /*generate the array elements (items).*/
call gen /*generate the array elements (items).*/
call show 'before sort' /*show the before array elements. */
call show 'before sort' /*show the before array elements. */
Line 5,223: Line 5,223:
return
return
/*──────────────────────────────────────────────────────────────────────────────────────*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
show: do j=1 for #; say ' element' right(j,length(#)) arg(1)":" @.j; end; return</lang>
show: do j=1 for #; say ' element' right(j,length(#)) arg(1)":" @.j; end; return</syntaxhighlight>
{{out|output|text=&nbsp; when using the internal array list:}}
{{out|output|text=&nbsp; when using the internal array list:}}
<br>(Shown at &nbsp; '''<sup>5</sup>/<sub>6</sub>''' &nbsp; size.)
<br>(Shown at &nbsp; '''<sup>5</sup>/<sub>6</sub>''' &nbsp; size.)
Line 5,282: Line 5,282:


Programming note: &nbsp; a check was made to not exceed REXX's upper range limit of the &nbsp; '''random''' &nbsp; BIF.
Programming note: &nbsp; a check was made to not exceed REXX's upper range limit of the &nbsp; '''random''' &nbsp; BIF.
<lang rexx>/*REXX program sorts an array (of any kind of numbers) using the bubble─sort algorithm.*/
<syntaxhighlight lang="rexx">/*REXX program sorts an array (of any kind of numbers) using the bubble─sort algorithm.*/
parse arg N .; if N=='' | N=="," then N=30 /*obtain optional size of array from CL*/
parse arg N .; if N=='' | N=="," then N=30 /*obtain optional size of array from CL*/
call gen N /*generate the array elements (items). */
call gen N /*generate the array elements (items). */
Line 5,297: Line 5,297:
/*──────────────────────────────────────────────────────────────────────────────────────*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
gen: h=min(N+N,1e5); w=length(h); do j=1 for N; @.j=random(h); end; return
gen: h=min(N+N,1e5); w=length(h); do j=1 for N; @.j=random(h); end; return
show: parse arg $; do k=1 for N; $=$ right(@.k, w); end; say $; return</lang>
show: parse arg $; do k=1 for N; $=$ right(@.k, w); end; say $; return</syntaxhighlight>
{{out|output|text=&nbsp; when using a internally generated random array of thirty integers &nbsp; (which are right-justified for alignment in the display):}}
{{out|output|text=&nbsp; when using a internally generated random array of thirty integers &nbsp; (which are right-justified for alignment in the display):}}
<pre>
<pre>
Line 5,306: Line 5,306:
===version 2, random integers, horizontal list===
===version 2, random integers, horizontal list===
{{trans|PL/I}}
{{trans|PL/I}}
<lang rexx>
<syntaxhighlight lang="rexx">
/*REXX*/
/*REXX*/
Call random ,,1000
Call random ,,1000
Line 5,331: Line 5,331:
show:
show:
l=''; Do i=1 To a.0; l=l a.i; End; Say arg(1)':'l
l=''; Do i=1 To a.0; l=l a.i; End; Say arg(1)':'l
Return</lang>
Return</syntaxhighlight>
{{out}}
{{out}}
<pre>vorher : 9 17 16 19 5 7 3 20 16 0
<pre>vorher : 9 17 16 19 5 7 3 20 16 0
Line 5,347: Line 5,347:
Also note that only four snapshots of the sort-in-progress is shown here, &nbsp; the REXX program will show a snapshot of ''every''
Also note that only four snapshots of the sort-in-progress is shown here, &nbsp; the REXX program will show a snapshot of ''every''
<br>sorting pass; &nbsp; the &nbsp; &nbsp; &nbsp; ''at &nbsp; (about) &nbsp; nnn% sorted'' &nbsp; &nbsp; &nbsp; was added after-the-fact.
<br>sorting pass; &nbsp; the &nbsp; &nbsp; &nbsp; ''at &nbsp; (about) &nbsp; nnn% sorted'' &nbsp; &nbsp; &nbsp; was added after-the-fact.
<lang rexx>/*REXX program sorts an array (of any kind of numbers) using the bubble─sort algorithm.*/
<syntaxhighlight lang="rexx">/*REXX program sorts an array (of any kind of numbers) using the bubble─sort algorithm.*/
parse arg N seed . /*obtain optional size of array from CL*/
parse arg N seed . /*obtain optional size of array from CL*/
if N=='' | N=="," then N=30 /*Not specified? Then use the default.*/
if N=='' | N=="," then N=30 /*Not specified? Then use the default.*/
Line 5,378: Line 5,378:
do s=# for # by -1; say $.s; end /*s*/
do s=# for # by -1; say $.s; end /*s*/
say "└"copies('─', #) /*display the horizontal axis at bottom*/
say "└"copies('─', #) /*display the horizontal axis at bottom*/
return</lang>
return</syntaxhighlight>
{{out|output|text=&nbsp; when using the default input:}}
{{out|output|text=&nbsp; when using the default input:}}
<pre>
<pre>
Line 5,512: Line 5,512:


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>bubbleList = [4,2,1,3]
<syntaxhighlight lang="ring">bubbleList = [4,2,1,3]
flag = 0
flag = 0
bubbleSort(bubbleList)
bubbleSort(bubbleList)
Line 5,530: Line 5,530:
next
next
end
end
</syntaxhighlight>
</lang>


=={{header|Ruby}}==
=={{header|Ruby}}==
{{eff note|Ruby|Array.sort!}}This example adds the bubblesort! method to the Array object. Below are two different methods that show four different iterating constructs in ruby.
{{eff note|Ruby|Array.sort!}}This example adds the bubblesort! method to the Array object. Below are two different methods that show four different iterating constructs in ruby.


<lang ruby>class Array
<syntaxhighlight lang="ruby">class Array
def bubblesort1!
def bubblesort1!
length.times do |j|
length.times do |j|
Line 5,558: Line 5,558:
ary.bubblesort1!
ary.bubblesort1!
p ary
p ary
# => [3, 4, 6, 6, 8, 23, 78]</lang>
# => [3, 4, 6, 6, 8, 23, 78]</syntaxhighlight>


=={{header|Run BASIC}}==
=={{header|Run BASIC}}==
<lang runbasic>siz = 100
<syntaxhighlight lang="runbasic">siz = 100
dim data$(siz)
dim data$(siz)
unSorted = 1
unSorted = 1
Line 5,575: Line 5,575:
END IF
END IF
NEXT
NEXT
WEND</lang>
WEND</syntaxhighlight>


=={{header|Rust}}==
=={{header|Rust}}==
<lang rust>fn bubble_sort<T: Ord>(values: &mut[T]) {
<syntaxhighlight lang="rust">fn bubble_sort<T: Ord>(values: &mut[T]) {
let mut n = values.len();
let mut n = values.len();
let mut swapped = true;
let mut swapped = true;
Line 5,610: Line 5,610:
bubble_sort(&mut strings);
bubble_sort(&mut strings);
println!("After: {:?}", strings);
println!("After: {:?}", strings);
}</lang>
}</syntaxhighlight>


=={{header|Sather}}==
=={{header|Sather}}==
<lang sather>class SORT{T < $IS_LT{T}} is
<syntaxhighlight lang="sather">class SORT{T < $IS_LT{T}} is
private swap(inout a, inout b:T) is
private swap(inout a, inout b:T) is
temp ::= a;
temp ::= a;
Line 5,633: Line 5,633:
end;
end;
end;
end;
end;</lang>
end;</syntaxhighlight>


<lang sather>class MAIN is
<syntaxhighlight lang="sather">class MAIN is
main is
main is
a:ARRAY{INT} := |10, 9, 8, 7, 6, -10, 5, 4|;
a:ARRAY{INT} := |10, 9, 8, 7, 6, -10, 5, 4|;
Line 5,641: Line 5,641:
#OUT + a + "\n";
#OUT + a + "\n";
end;
end;
end;</lang>
end;</syntaxhighlight>


This should be able to sort (in ascending order) any object for which <code>is_lt</code> (less than) is defined.
This should be able to sort (in ascending order) any object for which <code>is_lt</code> (less than) is defined.
Line 5,649: Line 5,649:
This slightly more complex version of Bubble Sort avoids errors with indices.
This slightly more complex version of Bubble Sort avoids errors with indices.


<lang scala>def bubbleSort[T](arr: Array[T])(implicit o: Ordering[T]) {
<syntaxhighlight lang="scala">def bubbleSort[T](arr: Array[T])(implicit o: Ordering[T]) {
import o._
import o._
val consecutiveIndices = (arr.indices, arr.indices drop 1).zipped
val consecutiveIndices = (arr.indices, arr.indices drop 1).zipped
Line 5,664: Line 5,664:
}
}
} while(hasChanged)
} while(hasChanged)
}</lang>
}</syntaxhighlight>


<lang scala>import scala.annotation.tailrec
<syntaxhighlight lang="scala">import scala.annotation.tailrec


def bubbleSort(xt: List[Int]) = {
def bubbleSort(xt: List[Int]) = {
Line 5,679: Line 5,679:
}
}
bubble(xt, Nil, Nil)
bubble(xt, Nil, Nil)
}</lang>
}</syntaxhighlight>


=={{header|Scheme}}==
=={{header|Scheme}}==
<lang scheme>(define (bubble-sort x gt?)
<syntaxhighlight lang="scheme">(define (bubble-sort x gt?)
(letrec
(letrec
((fix (lambda (f i)
((fix (lambda (f i)
Line 5,696: Line 5,696:
(cons (car l) (sort-step (cdr l))))))))
(cons (car l) (sort-step (cdr l))))))))


(fix sort-step x)))</lang>
(fix sort-step x)))</syntaxhighlight>


This solution recursively finds the fixed point of sort-step. A comparison function must be passed to bubblesort. Example usages:
This solution recursively finds the fixed point of sort-step. A comparison function must be passed to bubblesort. Example usages:
<lang scheme>(bubble-sort (list 1 3 5 9 8 6 4 2) >)
<syntaxhighlight lang="scheme">(bubble-sort (list 1 3 5 9 8 6 4 2) >)
(bubble-sort (string->list "Monkey") char<?)</lang>
(bubble-sort (string->list "Monkey") char<?)</syntaxhighlight>


Here is the same function, using a different syntax:
Here is the same function, using a different syntax:


<lang scheme>(define (bsort l gt?)
<syntaxhighlight lang="scheme">(define (bsort l gt?)
(define (dosort l)
(define (dosort l)
(cond ((null? (cdr l))
(cond ((null? (cdr l))
Line 5,716: Line 5,716:
l
l
(bsort try gt?))))
(bsort try gt?))))
</syntaxhighlight>
</lang>
For example, you could do
For example, you could do
<lang scheme>(bsort > '(2 4 6 2))
<syntaxhighlight lang="scheme">(bsort > '(2 4 6 2))
(1 2 3)</lang>
(1 2 3)</syntaxhighlight>


=={{header|Scilab}}==
=={{header|Scilab}}==
<lang>function b=BubbleSort(a)
<syntaxhighlight lang="text">function b=BubbleSort(a)
n=length(a)
n=length(a)
swapped=%T
swapped=%T
Line 5,737: Line 5,737:
end
end
b=a
b=a
endfunction BubbleSort</lang>
endfunction BubbleSort</syntaxhighlight>
{{out}}
{{out}}
<pre style="height:20ex">-->y=[5 4 3 2 1]
<pre style="height:20ex">-->y=[5 4 3 2 1]
Line 5,750: Line 5,750:


=={{header|Seed7}}==
=={{header|Seed7}}==
<lang seed7>const proc: bubbleSort (inout array elemType: arr) is func
<syntaxhighlight lang="seed7">const proc: bubbleSort (inout array elemType: arr) is func
local
local
var boolean: swapped is FALSE;
var boolean: swapped is FALSE;
Line 5,767: Line 5,767:
end for;
end for;
until not swapped;
until not swapped;
end func;</lang>
end func;</syntaxhighlight>


Original source: [http://seed7.sourceforge.net/algorith/sorting.htm#bubbleSort]
Original source: [http://seed7.sourceforge.net/algorith/sorting.htm#bubbleSort]
Line 5,773: Line 5,773:
=={{header|Shen}}==
=={{header|Shen}}==
Bubble sort a vector in-place, using the < operator for comparison.
Bubble sort a vector in-place, using the < operator for comparison.
<lang shen>(tc +)
<syntaxhighlight lang="shen">(tc +)


(define swap
(define swap
Line 5,799: Line 5,799:
{ (vector number) --> (vector number) }
{ (vector number) --> (vector number) }
A -> (let N (limit A)
A -> (let N (limit A)
(bubble-h (one-pass A N false 2) A N)))</lang>
(bubble-h (one-pass A N false 2) A N)))</syntaxhighlight>


<lang shen>(datatype some-globals
<syntaxhighlight lang="shen">(datatype some-globals


__________
__________
Line 5,812: Line 5,812:
(vector-> (value *arr*) 4 2)
(vector-> (value *arr*) 4 2)
(vector-> (value *arr*) 5 8)
(vector-> (value *arr*) 5 8)
(bubble-sort (value *arr*))</lang>
(bubble-sort (value *arr*))</syntaxhighlight>


Here is a more idiomatic implementation:
Here is a more idiomatic implementation:
{{trans|Qi}}
{{trans|Qi}}


<lang shen>(tc +)
<syntaxhighlight lang="shen">(tc +)


(define bubble-shot
(define bubble-shot
Line 5,827: Line 5,827:
(define bubble-sort
(define bubble-sort
{ (vector number) --> (vector number) }
{ (vector number) --> (vector number) }
X -> (fix (function bubble-shot) X))</lang>
X -> (fix (function bubble-shot) X))</syntaxhighlight>


<lang shen>(bubble-sort (@v 5 1 4 2 3 <>))</lang>
<syntaxhighlight lang="shen">(bubble-sort (@v 5 1 4 2 3 <>))</syntaxhighlight>


=={{header|Sidef}}==
=={{header|Sidef}}==
<lang ruby>func bubble_sort(arr) {
<syntaxhighlight lang="ruby">func bubble_sort(arr) {
loop {
loop {
var swapped = false
var swapped = false
Line 5,844: Line 5,844:
}
}
return arr
return arr
}</lang>
}</syntaxhighlight>


=={{header|Simula}}==
=={{header|Simula}}==
<lang simula>BEGIN
<syntaxhighlight lang="simula">BEGIN


PROCEDURE BUBBLESORT(A); NAME A; INTEGER ARRAY A;
PROCEDURE BUBBLESORT(A); NAME A; INTEGER ARRAY A;
Line 5,891: Line 5,891:
OUTIMAGE;
OUTIMAGE;


END;</lang>
END;</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 5,900: Line 5,900:
A straight translation from the pseudocode above. Swap is done with a [[wp:Smalltalk#Code_blocks|block closure]].
A straight translation from the pseudocode above. Swap is done with a [[wp:Smalltalk#Code_blocks|block closure]].


<lang smalltalk>|item swap itemCount hasChanged|
<syntaxhighlight lang="smalltalk">|item swap itemCount hasChanged|
item := #(1 4 5 6 10 8 7 61 0 -3) copy.
item := #(1 4 5 6 10 8 7 61 0 -3) copy.
swap :=
swap :=
Line 5,917: Line 5,917:
[swap value: index value: index + 1.
[swap value: index value: index + 1.
hasChanged := true]].
hasChanged := true]].
hasChanged] whileTrue.</lang>
hasChanged] whileTrue.</syntaxhighlight>


=={{header|SNOBOL4}}==
=={{header|SNOBOL4}}==


<lang SNOBOL4>* # Sort array in place, return array
<syntaxhighlight lang="snobol4">* # Sort array in place, return array
define('bubble(a,alen)i,j,ub,tmp') :(bubble_end)
define('bubble(a,alen)i,j,ub,tmp') :(bubble_end)
bubble i = 1; ub = alen
bubble i = 1; ub = alen
Line 5,944: Line 5,944:
sloop j = j + 1; str = str arr<j> ' ' :s(sloop)
sloop j = j + 1; str = str arr<j> ' ' :s(sloop)
output = trim(str)
output = trim(str)
end</lang>
end</syntaxhighlight>


{{out}}
{{out}}
Line 5,956: Line 5,956:


Static analysis of this code shows that it is guaranteed free of any run-time error when called from any other SPARK code.
Static analysis of this code shows that it is guaranteed free of any run-time error when called from any other SPARK code.
<lang Ada>package Bubble
<syntaxhighlight lang="ada">package Bubble
is
is


Line 5,992: Line 5,992:


end Bubble;
end Bubble;
</syntaxhighlight>
</lang>
The next version has a postcondition to guarantee that the returned array is sorted correctly. This requires the two proof rules that follow the source. The Ada code is identical with the first version.
The next version has a postcondition to guarantee that the returned array is sorted correctly. This requires the two proof rules that follow the source. The Ada code is identical with the first version.
<lang Ada>package Bubble
<syntaxhighlight lang="ada">package Bubble
is
is
Line 6,043: Line 6,043:
end Bubble;
end Bubble;
</syntaxhighlight>
</lang>
The proof rules are stated here without justification (but they are fairly obvious). A formal proof of these rules from the definition of Sorted has been completed.
The proof rules are stated here without justification (but they are fairly obvious). A formal proof of these rules from the definition of Sorted has been completed.
<pre>
<pre>
Line 6,058: Line 6,058:


The final version scans over a reducing portion of the array in the inner loop, consequently the proof becomes more complex. The package specification for this version is the same as the second version above. The package body defines two more proof functions.
The final version scans over a reducing portion of the array in the inner loop, consequently the proof becomes more complex. The package specification for this version is the same as the second version above. The package body defines two more proof functions.
<lang Ada>package body Bubble
<syntaxhighlight lang="ada">package body Bubble
is
is
procedure Sort (A : in out Arr)
procedure Sort (A : in out Arr)
Line 6,121: Line 6,121:


end Bubble;
end Bubble;
</syntaxhighlight>
</lang>
Completion of the proof of this version requires more rules than the previous version and they are rather more complex. Creation of these rules is quite straightforward - I tend to write whatever rules the Simplifier needs first and then validate them afterwards. A formal proof of these rules from the definition of Sorted, In_Position and Swapped has been completed.
Completion of the proof of this version requires more rules than the previous version and they are rather more complex. Creation of these rules is quite straightforward - I tend to write whatever rules the Simplifier needs first and then validate them afterwards. A formal proof of these rules from the definition of Sorted, In_Position and Swapped has been completed.
<pre>bubble_sort_rule(1): sorted(A, I, J)
<pre>bubble_sort_rule(1): sorted(A, I, J)
Line 6,195: Line 6,195:


File '''bubble.ads''':
File '''bubble.ads''':
<lang ada>package Bubble with SPARK_Mode is
<syntaxhighlight lang="ada">package Bubble with SPARK_Mode is


type Arr is array (Integer range <>) of Integer;
type Arr is array (Integer range <>) of Integer;
Line 6,217: Line 6,217:
end Bubble;
end Bubble;
</syntaxhighlight>
</lang>


File '''bubble.adb''':
File '''bubble.adb''':
<lang ada>package body Bubble with SPARK_Mode is
<syntaxhighlight lang="ada">package body Bubble with SPARK_Mode is
procedure Sort (A : in out Arr)
procedure Sort (A : in out Arr)
Line 6,254: Line 6,254:
end Bubble;
end Bubble;
</syntaxhighlight>
</lang>


File '''main.adb''':
File '''main.adb''':
<lang ada>with Ada.Integer_Text_IO;
<syntaxhighlight lang="ada">with Ada.Integer_Text_IO;
with Bubble;
with Bubble;


Line 6,268: Line 6,268:
end loop;
end loop;
end Main;
end Main;
</syntaxhighlight>
</lang>


File '''bubble.gpr''':
File '''bubble.gpr''':
<lang ada>project Bubble is
<syntaxhighlight lang="ada">project Bubble is


for Main use ("main.adb");
for Main use ("main.adb");


end Bubble;
end Bubble;
</syntaxhighlight>
</lang>


To verify the program, execute the command: '''gnatprove -P bubble.gpr -j0 --level=2'''
To verify the program, execute the command: '''gnatprove -P bubble.gpr -j0 --level=2'''
Line 6,322: Line 6,322:


=={{header|Stata}}==
=={{header|Stata}}==
<lang stata>mata
<syntaxhighlight lang="stata">mata
function bubble_sort(a) {
function bubble_sort(a) {
n = length(a)
n = length(a)
Line 6,338: Line 6,338:
}
}
}
}
end</lang>
end</syntaxhighlight>


=={{header|Swift}}==
=={{header|Swift}}==
<lang Swift>func bubbleSort<T:Comparable>(list:inout[T]) {
<syntaxhighlight lang="swift">func bubbleSort<T:Comparable>(list:inout[T]) {
var done = false
var done = false
while !done {
while !done {
Line 6,357: Line 6,357:
print(list1)
print(list1)
bubbleSort(list: &list1)
bubbleSort(list: &list1)
print(list1)</lang>
print(list1)</syntaxhighlight>


=={{header|Symsyn}}==
=={{header|Symsyn}}==
<syntaxhighlight lang="symsyn">
<lang Symsyn>


x : 23 : 15 : 99 : 146 : 3 : 66 : 71 : 5 : 23 : 73 : 19
x : 23 : 15 : 99 : 146 : 3 : 66 : 71 : 5 : 23 : 73 : 19
Line 6,405: Line 6,405:
" $r $s " []
" $r $s " []
return
return
</syntaxhighlight>
</lang>


=={{header|Tailspin}}==
=={{header|Tailspin}}==
<lang tailspin>
<syntaxhighlight lang="tailspin">
templates bubblesort
templates bubblesort
templates bubble
templates bubble
Line 6,430: Line 6,430:
[4,5,3,8,1,2,6,7,9,8,5] -> bubblesort -> !OUT::write
[4,5,3,8,1,2,6,7,9,8,5] -> bubblesort -> !OUT::write
</syntaxhighlight>
</lang>


=={{header|Tcl}}==
=={{header|Tcl}}==
{{tcllib|struct::list}}
{{tcllib|struct::list}}
<lang tcl>package require Tcl 8.5
<syntaxhighlight lang="tcl">package require Tcl 8.5
package require struct::list
package require struct::list


Line 6,454: Line 6,454:
}
}


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


Idiomatic code uses the builtin <code>lsort</code> instead, which is a stable O(''n'' log ''n'') sort.
Idiomatic code uses the builtin <code>lsort</code> instead, which is a stable O(''n'' log ''n'') sort.
Line 6,558: Line 6,558:
Toka does not have a bubble sort predefined, but it is easy to code a simple one:
Toka does not have a bubble sort predefined, but it is easy to code a simple one:


<lang toka>#! A simple Bubble Sort function
<syntaxhighlight lang="toka">#! A simple Bubble Sort function
value| array count changed |
value| array count changed |
[ ( address count -- )
[ ( address count -- )
Line 6,595: Line 6,595:
foo 10 .array
foo 10 .array
foo 10 bsort
foo 10 bsort
foo 10 .array</lang>
foo 10 .array</syntaxhighlight>


=={{header|TorqueScript}}==
=={{header|TorqueScript}}==


<lang TorqueScript>//Note that we're assuming that the list of numbers is separated by tabs.
<syntaxhighlight lang="torquescript">//Note that we're assuming that the list of numbers is separated by tabs.
function bubbleSort(%list)
function bubbleSort(%list)
{
{
Line 6,616: Line 6,616:
}
}
return %list;
return %list;
}</lang>
}</syntaxhighlight>


=={{header|uBasic/4tH}}==
=={{header|uBasic/4tH}}==
<lang>PRINT "Bubble sort:"
<syntaxhighlight lang="text">PRINT "Bubble sort:"
n = FUNC (_InitArray)
n = FUNC (_InitArray)
PROC _ShowArray (n)
PROC _ShowArray (n)
Line 6,666: Line 6,666:
PRINT
PRINT
RETURN</lang>
RETURN</syntaxhighlight>


=={{header|Unicon}}==
=={{header|Unicon}}==
Line 6,672: Line 6,672:


=={{header|UnixPipes}}==
=={{header|UnixPipes}}==
<lang bash>rm -f _sortpass
<syntaxhighlight lang="bash">rm -f _sortpass


reset() {
reset() {
Line 6,694: Line 6,694:
}
}


cat to.sort | bubblesort</lang>
cat to.sort | bubblesort</syntaxhighlight>


=={{header|Ursala}}==
=={{header|Ursala}}==
The bubblesort function is parameterized by a relational predicate.
The bubblesort function is parameterized by a relational predicate.
<lang Ursala>#import nat
<syntaxhighlight lang="ursala">#import nat


bubblesort "p" = @iNX ^=T ^llPrEZryPrzPlrPCXlQ/~& @l ~&aitB^?\~&a "p"?ahthPX/~&ahPfatPRC ~&ath2fahttPCPRC
bubblesort "p" = @iNX ^=T ^llPrEZryPrzPlrPCXlQ/~& @l ~&aitB^?\~&a "p"?ahthPX/~&ahPfatPRC ~&ath2fahttPCPRC
Line 6,704: Line 6,704:
#cast %nL
#cast %nL


example = bubblesort(nleq) <362,212,449,270,677,247,567,532,140,315></lang>
example = bubblesort(nleq) <362,212,449,270,677,247,567,532,140,315></syntaxhighlight>
{{out}}
{{out}}
<pre><140,212,247,270,315,362,449,532,567,677></pre>
<pre><140,212,247,270,315,362,449,532,567,677></pre>


=={{header|Vala}}==
=={{header|Vala}}==
<lang vala>void swap(int[] array, int i1, int i2) {
<syntaxhighlight lang="vala">void swap(int[] array, int i1, int i2) {
if (array[i1] == array[i2])
if (array[i1] == array[i2])
return;
return;
Line 6,737: Line 6,737:
foreach (int i in array)
foreach (int i in array)
print("%d ", i);
print("%d ", i);
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 6,744: Line 6,744:


=={{header|VBA}}==
=={{header|VBA}}==
{{trans|Phix}}<lang vb>Private Function bubble_sort(s As Variant) As Variant
{{trans|Phix}}<syntaxhighlight lang="vb">Private Function bubble_sort(s As Variant) As Variant
Dim tmp As Variant
Dim tmp As Variant
Dim changed As Boolean
Dim changed As Boolean
Line 6,770: Line 6,770:
Debug.Print "After: "
Debug.Print "After: "
Debug.Print Join(bubble_sort(s), ", ")
Debug.Print Join(bubble_sort(s), ", ")
End Sub</lang>{{out}}
End Sub</syntaxhighlight>{{out}}
<pre>Before:
<pre>Before:
4, 15, delta, 2, -31, 0, alfa, 19, gamma, 2, 13, beta, 782, 1
4, 15, delta, 2, -31, 0, alfa, 19, gamma, 2, 13, beta, 782, 1
Line 6,782: Line 6,782:


=====Implementation=====
=====Implementation=====
<syntaxhighlight lang="vb">
<lang vb>
sub decr( byref n )
sub decr( byref n )
n = n - 1
n = n - 1
Line 6,814: Line 6,814:
bubbleSort = a
bubbleSort = a
end function
end function
</syntaxhighlight>
</lang>


=====Invocation=====
=====Invocation=====
<syntaxhighlight lang="vb">
<lang vb>
dim a
dim a
a = array( "great eastern", "roe", "stirling", "albany", "leach")
a = array( "great eastern", "roe", "stirling", "albany", "leach")
Line 6,823: Line 6,823:
bubbleSort a
bubbleSort a
wscript.echo join(a,", ")
wscript.echo join(a,", ")
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 6,835: Line 6,835:


{{works with|Visual Basic .NET|9.0+}}
{{works with|Visual Basic .NET|9.0+}}
<lang vbnet>Do Until NoMoreSwaps = True
<syntaxhighlight lang="vbnet">Do Until NoMoreSwaps = True
NoMoreSwaps = True
NoMoreSwaps = True
For Counter = 1 To (NumberOfItems - 1)
For Counter = 1 To (NumberOfItems - 1)
Line 6,846: Line 6,846:
Next
Next
NumberOfItems = NumberOfItems - 1
NumberOfItems = NumberOfItems - 1
Loop</lang>
Loop</syntaxhighlight>


=={{header|Vlang}}==
=={{header|Vlang}}==
<lang vlang>fn bubble(mut arr []int) {
<syntaxhighlight lang="vlang">fn bubble(mut arr []int) {
println('Input: ${arr.str()}')
println('Input: ${arr.str()}')
mut count := arr.len
mut count := arr.len
Line 6,876: Line 6,876:
mut arr := [3, 5, 2, 1, 4]
mut arr := [3, 5, 2, 1, 4]
bubble(mut arr)
bubble(mut arr)
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>Input: [3, 5, 2, 1, 4]
<pre>Input: [3, 5, 2, 1, 4]
Line 6,883: Line 6,883:
=={{header|Wren}}==
=={{header|Wren}}==
Based on the pseudo-code in the Wikipedia article.
Based on the pseudo-code in the Wikipedia article.
<lang ecmascript>var bubbleSort = Fn.new { |a|
<syntaxhighlight lang="ecmascript">var bubbleSort = Fn.new { |a|
var n = a.count
var n = a.count
if (n < 2) return
if (n < 2) return
Line 6,906: Line 6,906:
System.print("After : %(a)")
System.print("After : %(a)")
System.print()
System.print()
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 6,919: Line 6,919:
=={{header|X86 Assembly}}==
=={{header|X86 Assembly}}==
Translation of XPL0. Assemble with tasm, tlink /t
Translation of XPL0. Assemble with tasm, tlink /t
<lang asm> .model tiny
<syntaxhighlight lang="asm"> .model tiny
.code
.code
.486
.486
Line 6,948: Line 6,948:
popa
popa
ret
ret
end start</lang>
end start</syntaxhighlight>


{{out}}
{{out}}
Line 6,956: Line 6,956:


=={{header|Xojo}}==
=={{header|Xojo}}==
<lang xojo>Dim temp, count As Integer
<syntaxhighlight lang="xojo">Dim temp, count As Integer
Dim isDirty As Boolean
Dim isDirty As Boolean
count = Ubound(list) // count the array size
count = Ubound(list) // count the array size
Line 6,971: Line 6,971:
End
End
Next
Next
Loop Until isDirty = False // if we made it without touching the data then we are done</lang>
Loop Until isDirty = False // if we made it without touching the data then we are done</syntaxhighlight>


=={{header|XPL0}}==
=={{header|XPL0}}==
<lang XPL0>include c:\cxpl\codes; \intrinsic 'code' declarations
<syntaxhighlight lang="xpl0">include c:\cxpl\codes; \intrinsic 'code' declarations
string 0; \use zero-terminated strings
string 0; \use zero-terminated strings


Line 6,997: Line 6,997:
BSort(Str, StrLen(Str));
BSort(Str, StrLen(Str));
Text(0, Str); CrLf(0);
Text(0, Str); CrLf(0);
]</lang>
]</syntaxhighlight>


{{out}}
{{out}}
Line 7,005: Line 7,005:


=={{header|Yabasic}}==
=={{header|Yabasic}}==
<lang Yabasic>// Animated sort.
<syntaxhighlight lang="yabasic">// Animated sort.
// Original idea by William Tang, obtained from MicroHobby 25 Years (https://microhobby.speccy.cz/zxsf/MH-25Years.pdf)
// Original idea by William Tang, obtained from MicroHobby 25 Years (https://microhobby.speccy.cz/zxsf/MH-25Years.pdf)


Line 7,045: Line 7,045:


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


=={{header|Yorick}}==
=={{header|Yorick}}==
<lang yorick>func bubblesort(&items) {
<syntaxhighlight lang="yorick">func bubblesort(&items) {
itemCount = numberof(items);
itemCount = numberof(items);
do {
do {
Line 7,060: Line 7,060:
}
}
} while(hasChanged);
} while(hasChanged);
}</lang>
}</syntaxhighlight>


=={{header|zkl}}==
=={{header|zkl}}==
<lang zkl>fcn bubbleSort(list){
<syntaxhighlight lang="zkl">fcn bubbleSort(list){
itemCount := list.len();
itemCount := list.len();
do{
do{
Line 7,075: Line 7,075:
}while(hasChanged);
}while(hasChanged);
list
list
}</lang>
}</syntaxhighlight>
Or, punting early termination:
Or, punting early termination:
<lang zkl>fcn bubbleSort(list){
<syntaxhighlight lang="zkl">fcn bubbleSort(list){
foreach n,index in ([list.len()-1..0,-1],n){
foreach n,index in ([list.len()-1..0,-1],n){
if (list[index] > list[index + 1]) list.swap(index,index + 1);
if (list[index] > list[index + 1]) list.swap(index,index + 1);
}
}
list
list
}</lang>
}</syntaxhighlight>
<lang zkl>bubbleSort("This is a test".split("")).println();</lang>
<syntaxhighlight lang="zkl">bubbleSort("This is a test".split("")).println();</syntaxhighlight>
{{out}}
{{out}}
<pre>L(" "," "," ","T","a","e","h","i","i","s","s","s","t","t")</pre>
<pre>L(" "," "," ","T","a","e","h","i","i","s","s","s","t","t")</pre>


=={{header|ZX Spectrum Basic}}==
=={{header|ZX Spectrum Basic}}==
<lang zxbasic>5000 CLS
<syntaxhighlight lang="zxbasic">5000 CLS
5002 LET a$="": FOR f=1 TO 64: LET a$=a$+CHR$ (32+INT (RND*96)): NEXT f
5002 LET a$="": FOR f=1 TO 64: LET a$=a$+CHR$ (32+INT (RND*96)): NEXT f
5004 PRINT a$; AT 10,0;"ZigZag BubbleSORT"
5004 PRINT a$; AT 10,0;"ZigZag BubbleSORT"
Line 7,108: Line 7,108:
5064 IF d AND i<la THEN GO TO 5020
5064 IF d AND i<la THEN GO TO 5020
5072 PRINT AT 12,0;a$
5072 PRINT AT 12,0;a$
9000 STOP </lang>
9000 STOP </syntaxhighlight>


The traditional solution:
The traditional solution:


<lang zxbasic> 10 LET siz=32
<syntaxhighlight lang="zxbasic"> 10 LET siz=32
20 DIM d$(siz)
20 DIM d$(siz)
30 REM Populate d$
30 REM Populate d$
Line 7,122: Line 7,122:
90 NEXT i
90 NEXT i
100 IF unSorted THEN LET siz=siz-1: GO TO 60
100 IF unSorted THEN LET siz=siz-1: GO TO 60
110 PRINT d$</lang>
110 PRINT d$</syntaxhighlight>


{{omit from|GUISS}}
{{omit from|GUISS}}