Sorting algorithms/Bubble sort: Difference between revisions

m
→‎{{header|Standard ML}}: fix syntax highlighting
m (→‎{{header|R}}: Syntax highlighting.)
m (→‎{{header|Standard ML}}: fix syntax highlighting)
 
(47 intermediate revisions by 21 users not shown)
Line 5:
 
A   '''bubble'''   sort is also known as a   '''sinking'''   sort.
 
 
Because of its simplicity and ease of visualization, it is often taught in introductory computer science courses.
Line 40 ⟶ 39:
{{trans|Python}}
 
<langsyntaxhighlight lang="11l">F bubble_sort(&seq)
V changed = 1B
L changed == 1B
Line 54 ⟶ 53:
assert(testcase != testset)
bubble_sort(&testcase)
assert(testcase == testset)</langsyntaxhighlight>
 
=={{header|360 Assembly}}==
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.
<langsyntaxhighlight lang="360 Assemblyassembly">* Bubble Sort 01/11/2014 & 23/06/2016
BUBBLE CSECT
USING BUBBLE,R13,R12 establish base registers
Line 117 ⟶ 116:
RN EQU 7 n-1
RM EQU 8 more
END BUBBLE</langsyntaxhighlight>
{{out}}
<pre>
Line 124 ⟶ 123:
=={{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. ;)
<langsyntaxhighlight lang="6502asm">define z_HL $00
define z_L $00
define z_H $01
Line 178 ⟶ 177:
jmp BUBBLESORT
DoneSorting:
rts</langsyntaxhighlight>
{{out}}
<pre>
Line 201 ⟶ 200:
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang="aarch64 assembly">
<lang AArch64 Assembly>
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program bubbleSort64.s */
Line 371 ⟶ 370:
.include "../includeARM64.inc"
 
</syntaxhighlight>
</lang>
=={{header|ACL2}}==
<langsyntaxhighlight Lisplang="lisp">(defun bubble (xs)
(if (endp (rest xs))
(mv nil xs)
Line 398 ⟶ 397:
 
(defun bsort (xs)
(bsort-r xs (len xs)))</langsyntaxhighlight>
 
=={{header|Action!}}==
<langsyntaxhighlight Actionlang="action!">PROC PrintArray(INT ARRAY a INT size)
INT i
 
Line 456 ⟶ 455:
Test(c,8)
Test(d,12)
RETURN</langsyntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Bubble_sort.png Screenshot from Atari 8-bit computer]
Line 482 ⟶ 481:
 
=={{header|ActionScript}}==
<langsyntaxhighlight lang="actionscript">public function bubbleSort(toSort:Array):Array
{
var changed:Boolean = false;
Line 504 ⟶ 503:
return toSort;
}</langsyntaxhighlight>
 
=={{header|Ada}}==
{{works with|GCC|4.1.2}}
 
<langsyntaxhighlight lang="ada">generic
type Element is private;
with function "=" (E1, E2 : Element) return Boolean is <>;
Line 552 ⟶ 551:
end loop;
New_Line;
end Main;</langsyntaxhighlight>
 
=={{header|ALGOL 60}}==
{{works with|A60}}
<langsyntaxhighlight lang="algol60">begin
comment Sorting algorithms/Bubble sort - Algol 60;
integer nA;
Line 603 ⟶ 602:
writetable(1,nA)
end
end </langsyntaxhighlight>
{{out}}
<pre>
Line 611 ⟶ 610:
 
=={{header|ALGOL 68}}==
<langsyntaxhighlight lang="algol68">MODE DATA = INT;
PROC swap = (REF[]DATA slice)VOID:
(
Line 642 ⟶ 641:
sort(random);
printf(($"After: "10(g(3))l$,random))
)</langsyntaxhighlight>
{{out}}
<pre>
Line 650 ⟶ 649:
 
=={{header|ALGOL W}}==
<langsyntaxhighlight lang="algolw">begin
% As algol W does not allow overloading, we have to have type-specific %
% sorting procedures - this bubble sorts an integer array %
Line 709 ⟶ 708:
writeData;
end test
end.</langsyntaxhighlight>
{{out}}
<pre>
Line 720 ⟶ 719:
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.
 
<langsyntaxhighlight lang="applescript">-- In-place bubble sort.
on bubbleSort(theList, l, r) -- Sort items l thru r of theList.
set listLen to (count theList)
Line 757 ⟶ 756:
set aList to {61, 23, 11, 55, 1, 94, 71, 98, 70, 33, 29, 77, 58, 95, 2, 52, 68, 29, 27, 37, 74, 38, 45, 73, 10}
sort(aList, 1, -1) -- Sort items 1 thru -1 of aList.
return aList</langsyntaxhighlight>
 
{{output}}
<langsyntaxhighlight 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}</langsyntaxhighlight>
 
=={{header|Arendelle}}==
Line 794 ⟶ 793:
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
<lang ARM Assembly>
 
/* ARM assembly Raspberry PI */
Line 952 ⟶ 951:
/***************************************************/
.include "../affichage.inc"
</syntaxhighlight>
</lang>
=={{header|Arturo}}==
 
<langsyntaxhighlight lang="rebol">bubbleSort: function [items][
len: size items
loop len [j][
Line 971 ⟶ 970:
]
 
print bubbleSort [3 1 2 8 5 7 9 4 6]</langsyntaxhighlight>
 
{{out}}
Line 978 ⟶ 977:
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">var =
(
dog
Line 1,012 ⟶ 1,011:
sorted .= array%A_Index% . "`n"
Return sorted
}</langsyntaxhighlight>
 
=={{header|AWK}}==
Sort the standard input and print it to standard output.
<langsyntaxhighlight lang="awk">{ # read every line into an array
line[NR] = $0
}
Line 1,035 ⟶ 1,034:
print line[i]
}
}</langsyntaxhighlight>
 
GNU awk contains built in functions for sorting, but POSIX
Line 1,046 ⟶ 1,045:
variables.
 
<langsyntaxhighlight lang="awk">
# Test this example file from command line with:
#
Line 1,092 ⟶ 1,091:
exit
}
</syntaxhighlight>
</lang>
 
=={{header|bash}}==
Line 1,098 ⟶ 1,097:
I hope to see vastly improved versions of bubble_sort.
 
<langsyntaxhighlight lang="bash">
$ function bubble_sort() {
local a=("$@")
Line 1,139 ⟶ 1,138:
-31 0 1 2 2 4 45 58 65 69 74 82 82 83 88 89 99 104 112 782
$
</syntaxhighlight>
</lang>
 
=={{header|BASIC}}==
{{works with|QuickBasic|4.5}}
 
{{trans|Java}}
Assume numbers are in a DIM of size "size" called "nums".
<lang qbasic>
DO
changed = 0
FOR I = 1 to size -1
IF nums(I) > nums(I + 1) THEN
tmp = nums(I)
nums(I) = nums(I + 1)
nums(I + 1) = tmp
changed = 1
END IF
NEXT
LOOP WHILE(NOT changed)</lang>
 
==={{header|Applesoft BASIC}}===
<langsyntaxhighlight lang="basic">0 GOSUB 7 : IC = I%(0)
1 FOR HC = -1 TO 0
2 LET IC = IC - 1
Line 1,169 ⟶ 1,151:
7 DIM I%(18000) : I%(0) = 50
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</langsyntaxhighlight>
 
==={{header|Sinclair ZX81 BASICBaCon}}===
Numeric example:
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.
<syntaxhighlight lang="bacon">LOCAL t[] = { 5, 7, 1, 3, 10, 2, 9, 4, 8, 6 }
<lang basic> 10 LET S$="FIRE BURN AND CAULDRON BUBBLE"
total = 10
20 PRINT S$
WHILE total > 1
30 LET L=LEN S$-1
FOR x = 0 TO total-1
40 LET C=0
IF t[x] > t[x+1] THEN SWAP t[x], t[x+1]
50 FOR I=1 TO L
NEXT
60 IF S$(I)<=S$(I+1) THEN GOTO 120
DECR total
70 LET T$=S$(I)
WEND
80 LET S$(I)=S$(I+1)
PRINT COIL$(10, STR$(t[_-1]))</syntaxhighlight>
90 LET S$(I+1)=T$
100 PRINT AT 0,I-1;S$(I TO I+1)
110 LET C=1
120 NEXT I
130 LET L=L-1
140 IF C THEN GOTO 40</lang>
{{out}}
<pre>1 2 3 4 AABBBBCDDEEFILLNNNORRRUUU5 6 7 8 9 10</pre>
String example:
<syntaxhighlight lang="bacon">t$ = "Kiev Amsterdam Lima Moscow Warschau Vienna Paris Madrid Bonn Bern Rome"
total = AMOUNT(t$)
WHILE total > 1
FOR x = 1 TO total-1
IF TOKEN$(t$, x) > TOKEN$(t$, x+1) THEN t$ = EXCHANGE$(t$, x, x+1)
NEXT
DECR total
WEND
PRINT t$</syntaxhighlight>
{{out}}
<pre>Amsterdam Bern Bonn Kiev Lima Madrid Moscow Paris Rome Vienna Warschau</pre>
 
==={{header|BASIC256}}===
{{works with|BASIC256 }}
<langsyntaxhighlight lang="basic256">
Dim a(11): ordered=false
print "Original set"
Line 1,217 ⟶ 1,206:
print a[n]+", ";
next n
</syntaxhighlight>
</lang>
{{out}}(example)
<pre>
Line 1,228 ⟶ 1,217:
==={{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.
<langsyntaxhighlight lang="bbcbasic"> DIM test(9)
test() = 4, 65, 2, -31, 0, 99, 2, 83, 782, 1
PROCbubblesort(test(), 10)
Line 1,249 ⟶ 1,238:
n% = l%
UNTIL l% = 0
ENDPROC</langsyntaxhighlight>
{{out}}
<pre>
Line 1,255 ⟶ 1,244:
</pre>
 
==={{header|Chipmunk Basic}}===
The [[#Commodore_BASIC|Commodore BASIC]] solution works without any changes.
 
==={{header|Commodore BASIC}}===
<syntaxhighlight lang="commodore">
<lang COMMODORE>
5 REM ===============================================
10 REM HTTP://ROSETTACODE.ORG/
Line 1,305 ⟶ 1,296:
910 DATA 15
920 DATA 64,34,25,12,22,11,90,13,59,47,19,89,10,17,31
</syntaxhighlight>
</lang>
 
==={{header|Craft Basic}}===
<syntaxhighlight lang="basic">define sort = 0, index = 0, size = 10
define temp1 = 0, temp2 = 0
 
dim list[size]
 
gosub fill
gosub sort
gosub show
 
end
 
sub fill
 
for index = 0 to size - 1
 
let list[index] = int(rnd * 100)
 
next index
 
return
 
sub sort
 
do
 
let sort = 0
for index = 0 to size - 2
 
let temp1 = index + 1
 
if list[index] > list[temp1] then
 
let temp2 = list[index]
let list[index] = list[temp1]
let list[temp1] = temp2
let sort = 1
 
endif
 
next index
 
wait
 
loop sort = 1
 
return
 
sub show
 
for index = 0 to size - 1
 
print index ," : ", list[index]
 
next index
 
return</syntaxhighlight>
 
==={{header|FreeBASIC}}===
Per task pseudo code:
<syntaxhighlight lang="freebasic">' version 21-10-2016
' compile with: fbc -s console
' for boundry checks on array's compile with: fbc -s console -exx
 
Sub bubblesort(bs() As Long)
' sort from lower bound to the highter bound
' array's can have subscript range from -2147483648 to +2147483647
Dim As Long lb = LBound(bs)
Dim As Long ub = UBound(bs)
Dim As Long done, i
 
Do
done = 0
For i = lb To ub -1
' replace "<" with ">" for downwards sort
If bs(i) > bs(i +1) Then
Swap bs(i), bs(i +1)
done = 1
End If
Next
Loop Until done = 0
 
End Sub
 
' ------=< MAIN >=------
 
Dim As Long i, array(-7 To 7)
 
Dim As Long a = LBound(array), b = UBound(array)
 
Randomize Timer
For i = a To b : array(i) = i : Next
For i = a To b ' little shuffle
Swap array(i), array(Int(Rnd * (b - a +1)) + a)
Next
 
Print "unsort ";
For i = a To b : Print Using "####"; array(i); : Next : Print
bubblesort(array()) ' sort the array
Print " sort ";
For i = a To b : Print Using "####"; array(i); : Next : Print
 
' empty keyboard buffer
While InKey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End</syntaxhighlight>
{{out}}
<pre>unsort -7 3 -4 -6 4 -1 -2 2 7 0 5 1 -3 -5 6
sort -7 -6 -5 -4 -3 -2 -1 0 1 2 3 4 5 6 7</pre>
 
==={{header|FTCBASIC}}===
<syntaxhighlight lang="basic">rem bubble sort benchmark example
rem compile with FTCBASIC
 
use time.inc
use random.inc
 
define const size = 32000
 
dim list[size]
 
define sorting = 0, index = 0, elements = 0
define timestamp = 0, sorttime = 0
define temp1 = 0, temp2 = 0
 
cls
 
print "Bubble sort benchmark test"
 
do
 
print "How many elements to generate and sort (max " \
print size \
print ")? " \
 
input elements
 
loop elements > size
 
gosub fill
gosub sort
 
print "done!"
print "sort time: " \
print sorttime
print "Press any key to view sorted data..."
 
pause
 
gosub output
 
pause
end
 
sub fill
 
print "filling..."
 
0 index
 
do
 
gosub generaterand
 
let @list[index] = rand
 
+1 index
 
loop index < elements
 
return
 
sub sort
 
print "sorting..."
 
gosub systemtime
let timestamp = loworder
 
do
 
0 sorting
 
0 index
 
do
 
let temp1 = index + 1
 
if @list[index] > @list[temp1] then
 
let temp2 = @list[index]
 
let @list[index] = @list[temp1]
let @list[temp1] = temp2
 
let sorting = 1
 
endif
 
+1 index
 
loop index < elements - 1
 
loop sorting = 1
 
gosub systemtime
let sorttime = ( loworder - timestamp ) / 18
 
return
 
sub output
 
print "printing..."
 
0 index
 
do
 
print @list[index]
 
+1 index
 
loop index < elements
 
return</syntaxhighlight>
 
==={{header|FutureBasic}}===
Bubble sorting is purely an academic exercise since there are much more efficient native sorting functions in FB.
<syntaxhighlight lang="futurebasic">
include "NSLog.incl"
 
local fn BubbleSort( array as CFMutableArrayRef ) as CFArrayRef
NSUInteger i, x, y, count = len(array)
BOOL swapped = YES
while (swapped)
swapped = NO
for i = 1 to count -1
x = fn NumberIntegerValue( array[i-1] )
y = fn NumberIntegerValue( array[i] )
if ( x > y )
MutableArrayExchangeObjects( array, (i-1), i )
swapped = YES
end if
next
wend
end fn = array
 
CFMutableArrayRef array
CFArrayRef unsortedArray, sortedArray
NSUInteger i
 
array = fn MutableArrayWithCapacity(0)
for i = 0 to 20
MutableArrayAddObject( array, fn NumberWithInteger( rnd(100) ) )
next
 
unsortedArray = fn ArrayWithArray( array )
sortedArray = fn BubbleSort( array )
 
NSLog( @"\n-----------------\nUnsorted : Sorted\n-----------------" )
for i = 0 to 20
NSLog( @"%8ld : %-8ld", fn NumberIntegerValue( unsortedArray[i] ), fn NumberIntegerValue( sortedArray[i] ) )
next
 
randomize
 
HandleEvents
</syntaxhighlight>
{{output}}
<pre>
-----------------
Unsorted : Sorted
-----------------
97 : 7
91 : 8
13 : 13
39 : 17
50 : 20
48 : 28
7 : 28
61 : 30
30 : 30
20 : 33
69 : 39
86 : 42
33 : 48
65 : 50
28 : 50
50 : 61
28 : 65
8 : 69
17 : 86
42 : 91
30 : 97
</pre>
 
==={{header|Gambas}}===
'''[https://gambas-playground.proko.eu/?gist=ba84832d633cb92bbe6c2f54704819c3 Click this link to run this code]'''
<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,
120, 19, 123, 2, 17, 226, 11, 211, 25, 191, 205, 77]
Dim byCount As Byte
Dim bSorting As Boolean
 
Print "To sort: -"
ShowWorking(byToSort)
Print
Repeat
bSorting = False
For byCount = 0 To byToSort.Max - 1
If byToSort[byCount] > byToSort[byCount + 1] Then
Swap byToSort[byCount], byToSort[byCount + 1]
bSorting = True
Endif
Next
If bSorting Then ShowWorking(byToSort)
Until bSorting = False
End
'-----------------------------------------
Public Sub ShowWorking(byToSort As Byte[])
Dim byCount As Byte
 
For byCount = 0 To byToSort.Max
Print Str(byToSort[byCount]);
If byCount <> byToSort.Max Then Print ",";
Next
 
Print
 
End</syntaxhighlight>
Output:
<pre>
To sort: -
249,28,111,36,171,98,29,192,44,147,154,46,102,183,24,120,19,123,2,17,226,11,211,25,191,205,77
 
28,111,36,171,98,29,192,44,147,154,46,102,183,24,120,19,123,2,17,226,11,211,25,191,205,77,249
28,36,111,98,29,171,44,147,154,46,102,183,24,120,19,123,2,17,192,11,211,25,191,205,77,226,249
28,36,98,29,111,44,147,154,46,102,171,24,120,19,123,2,17,183,11,192,25,191,205,77,211,226,249
28,36,29,98,44,111,147,46,102,154,24,120,19,123,2,17,171,11,183,25,191,192,77,205,211,226,249
28,29,36,44,98,111,46,102,147,24,120,19,123,2,17,154,11,171,25,183,191,77,192,205,211,226,249
28,29,36,44,98,46,102,111,24,120,19,123,2,17,147,11,154,25,171,183,77,191,192,205,211,226,249
28,29,36,44,46,98,102,24,111,19,120,2,17,123,11,147,25,154,171,77,183,191,192,205,211,226,249
28,29,36,44,46,98,24,102,19,111,2,17,120,11,123,25,147,154,77,171,183,191,192,205,211,226,249
28,29,36,44,46,24,98,19,102,2,17,111,11,120,25,123,147,77,154,171,183,191,192,205,211,226,249
28,29,36,44,24,46,19,98,2,17,102,11,111,25,120,123,77,147,154,171,183,191,192,205,211,226,249
28,29,36,24,44,19,46,2,17,98,11,102,25,111,120,77,123,147,154,171,183,191,192,205,211,226,249
28,29,24,36,19,44,2,17,46,11,98,25,102,111,77,120,123,147,154,171,183,191,192,205,211,226,249
28,24,29,19,36,2,17,44,11,46,25,98,102,77,111,120,123,147,154,171,183,191,192,205,211,226,249
24,28,19,29,2,17,36,11,44,25,46,98,77,102,111,120,123,147,154,171,183,191,192,205,211,226,249
24,19,28,2,17,29,11,36,25,44,46,77,98,102,111,120,123,147,154,171,183,191,192,205,211,226,249
19,24,2,17,28,11,29,25,36,44,46,77,98,102,111,120,123,147,154,171,183,191,192,205,211,226,249
19,2,17,24,11,28,25,29,36,44,46,77,98,102,111,120,123,147,154,171,183,191,192,205,211,226,249
2,17,19,11,24,25,28,29,36,44,46,77,98,102,111,120,123,147,154,171,183,191,192,205,211,226,249
2,17,11,19,24,25,28,29,36,44,46,77,98,102,111,120,123,147,154,171,183,191,192,205,211,226,249
2,11,17,19,24,25,28,29,36,44,46,77,98,102,111,120,123,147,154,171,183,191,192,205,211,226,249
</pre>
 
==={{header|GW-BASIC}}===
<langsyntaxhighlight lang="gwbasic">10 REM GENERATE A RANDOM BUNCH OF INTEGERS
20 DIM ARR(20)
30 RANDOMIZE TIMER
Line 1,331 ⟶ 1,682:
1020 ARR(I+1) = TEMP
1030 CHANGED = 1
1040 RETURN</langsyntaxhighlight>
{{out}}<pre>
20 59 42 9 5 91 6 64 21 28 65 96 20 66 66 70 91 98 63 31
Line 1,349 ⟶ 1,700:
 
==={{header|IS-BASIC}}===
<langsyntaxhighlight ISlang="is-BASICbasic">100 PROGRAM "BubblSrt.bas"
110 RANDOMIZE
120 NUMERIC ARRAY(-5 TO 9)
Line 1,374 ⟶ 1,725:
330 NEXT
340 LOOP WHILE CH
350 END DEF</langsyntaxhighlight>
 
==={{header|BaConLiberty BASIC}}===
{{works with|Just BASIC}}
Numeric example:
<syntaxhighlight lang="lb">
<lang bacon>LOCAL t[] = { 5, 7, 1, 3, 10, 2, 9, 4, 8, 6 }
totalitemCount = 1020
dim item(itemCount)
WHILE total > 1
for FOR xi = 01 TOto total-1itemCount
item(i) = int(rnd(1) * 100)
IF t[x] > t[x+1] THEN SWAP t[x], t[x+1]
next i
NEXT
print "Before Sort"
DECR total
for i = 1 to itemCount
WEND
print item(i)
PRINT COIL$(10, STR$(t[_-1]))</lang>
next i
print: print
counter = itemCount
do
hasChanged = 0
for i = 1 to counter - 1
if item(i) > item(i + 1) then
temp = item(i)
item(i) = item(i + 1)
item(i + 1) = temp
hasChanged = 1
end if
next i
counter =counter -1
loop while hasChanged = 1
print "After Sort"
for i = 1 to itemCount
print item(i)
next i
end
</syntaxhighlight>
 
==={{header|microA BASIC}}===
{{works with|microA }}
<syntaxhighlight lang="basic">
'bubble sort in micro(A) BASIC
wcolor 0,0,0 : fcolor 150,180,240
var start,endtime,time
var sort,index,size,temp1,temp2,x,xl,y
size = 1000 : x = 10 : y = 20 : xl = 40
var list[size]
index = 1
GETTICK start
'---------------------------------------------
label do1
list[index] = rand(100)
index = index + 1
if index < size : goto do1 : endif
'---------------------------------------------
label do2
sort = 0
index = 1
label do3
'---------------------------------------------
temp1 = index + 1
if list[index] > list[temp1]
temp2 = list[index]
list[index] = list[temp1]
list[temp1] = temp2
sort = 1
endif
index = index + 1
if index < size - 1 : goto do3 : endif
'-----------------------------------------------
if sort = 1 : goto do2 : endif
'-----------------------------------------------
index = 1
GETTICK endtime
time = (endTime - start) / 1000
fcolor 230,140,120: print 300,10,time : swap
index = 970
'check sort /////////////////////////////////////
label do4
print x,y ,index : print xl,y, list[index]
y = y + 20 : swap
index = index + 1
swap
if index < 1000 : goto do4 :endif
'////////////////////////////////////////////////
</syntaxhighlight>
 
==={{header|Minimal BASIC}}===
{{trans|QuickBASIC}}
{{works with|Bywater BASIC|2.61}}
<syntaxhighlight lang="basic">
100 REM Sorting algorithms/Bubble sort
110 REM Prepare data
120 REM N - size; A - array of nums
130 LET N = 10
140 OPTION BASE 1
150 DIM A(10)
160 RANDOMIZE
170 PRINT "Before: ";
180 FOR I = 1 TO N
190 LET A(I) = INT(RND*100)
200 PRINT A(I);
210 NEXT I
220 PRINT
230 REM Sort
240 REM C - counter; H - has changed
250 LET C = N
260 LET H = 0
270 FOR I = 1 TO C-1
280 IF A(I) <= A(I+1) THEN 330
290 LET T = A(I)
300 LET A(I) = A(I+1)
310 LET A(I+1) = T
320 LET H = 1
330 NEXT I
340 LET C = C-1
350 IF H = 1 THEN 260
360 REM Display result
370 PRINT "After: ";
380 FOR I = 1 TO N
390 PRINT A(I);
400 NEXT I
410 PRINT
420 END
</syntaxhighlight>
 
==={{header|PureBasic}}===
<syntaxhighlight lang="purebasic">Procedure bubbleSort(Array a(1))
Protected i, itemCount, hasChanged
itemCount = ArraySize(a())
Repeat
hasChanged = #False
itemCount - 1
For i = 0 To itemCount
If a(i) > a(i + 1)
Swap a(i), a(i + 1)
hasChanged = #True
EndIf
Next
Until hasChanged = #False
EndProcedure</syntaxhighlight>
 
==={{header|QuickBASIC}}===
{{works with|QBasic|1.1}}
{{works with|QuickBasic|4.5}}
<syntaxhighlight lang="qbasic">
' Sorting algorithms/Bubble sort
' Prepare data
size = 10
OPTION BASE 1
DIM nums(size)
RANDOMIZE TIMER
PRINT "Before:";
FOR I = 1 TO size
nums(I) = INT(RND * 100)
PRINT USING " ##"; nums(I);
NEXT I
PRINT
 
' Sort
counter = size
DO
changed = 0
FOR I = 1 TO counter - 1
IF nums(I) > nums(I + 1) THEN
tmp = nums(I)
nums(I) = nums(I + 1)
nums(I + 1) = tmp
changed = 1
END IF
NEXT I
counter = counter - 1
LOOP WHILE (changed)
 
' Display result
PRINT "After: ";
FOR I = 1 TO 10
PRINT USING " ##"; nums(I);
NEXT I
PRINT
END</syntaxhighlight>
{{out}} (2 samples)
<pre>Before: 91 97 3 62 17 48 89 7 2 66
After: 2 3 7 17 48 62 66 89 91 97</pre>
<pre>Before: 22 60 45 44 54 93 84 27 21 64
After: 21 22 27 44 45 54 60 64 84 93</pre>
 
==={{header|Quite BASIC}}===
<syntaxhighlight lang="qbasic">100 rem Sorting algorithms/Bubble sort
110 LET n = 10
120 array a
130 GOSUB 310
140 PRINT "unsort ";
150 GOSUB 360
160 rem Sort the array
170 GOSUB 210
180 PRINT " sort ";
190 GOSUB 360
200 END
210 rem Bubble sort the list A of length N
220 FOR i = 1 TO n-1
230 FOR j = 1 TO n-i
240 IF a[j] <= a[j+1] THEN GOTO 280
250 LET x = a[j]
260 LET a[j] = a[j+1]
270 LET a[j+1] = x
280 NEXT j
290 NEXT i
300 RETURN
310 rem Create a RANDOM list of N integers
320 FOR i = 1 TO n
330 LET a[i] = FLOOR(RAND(100))
340 NEXT i
350 RETURN
360 rem Print the list a
370 FOR i = 1 TO n
380 PRINT a[i];" ";
390 NEXT i
400 PRINT
410 RETURN</syntaxhighlight>
{{out}}
<pre>1unsort 2 319 478 539 654 763 868 966 52 94 2 10</pre>
sort 2 19 39 52 54 63 66 68 78 94 </pre>
String example:
 
<lang bacon>t$ = "Kiev Amsterdam Lima Moscow Warschau Vienna Paris Madrid Bonn Bern Rome"
==={{header|RapidQ}}===
total = AMOUNT(t$)
{{trans|QuickBASIC}}
WHILE total > 1
<syntaxhighlight lang="basic">
FOR x = 1 TO total-1
' Sorting algorithms/Bubble sort
IF TOKEN$(t$, x) > TOKEN$(t$, x+1) THEN t$ = EXCHANGE$(t$, x, x+1)
' Prepare data
size = 10
DIM nums(1 TO size)
RANDOMIZE TIMER
PRINT "Before:";
FOR I = 1 TO size
nums(I) = INT(RND * 100)
PRINT FORMAT$(" %2d", nums(I));
NEXT I
PRINT
 
' Sort
counter = size
DO
changed = 0
FOR I = 1 TO counter - 1
IF nums(I) > nums(I + 1) THEN
tmp = nums(I)
nums(I) = nums(I + 1)
nums(I + 1) = tmp
changed = -1
END IF
NEXT I
counter = counter - 1
LOOP UNTIL NOT changed
 
' Display result
PRINT "After: ";
FOR I = 1 TO 10
PRINT FORMAT$(" %2d", nums(I));
NEXT I
PRINT
END</syntaxhighlight>
{{out}} (2 samples)
<pre>Before: 82 34 57 44 48 71 19 33 73 62
After: 19 33 34 44 48 57 62 71 73 82</pre>
<pre>Before: 4 15 96 93 27 24 9 80 10 21
After: 4 9 10 15 21 24 27 80 93 96</pre>
 
==={{header|REALbasic}}===
Sorts an array of Integers.
<syntaxhighlight lang="vb">
Dim sortable() As Integer = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
sortable.Shuffle() ' sortable is now randomized
Dim swapped As Boolean
Do
Dim index, bound As Integer
bound = sortable.Ubound
 
While index < bound
If sortable(index) > sortable(index + 1) Then
Dim s As Integer = sortable(index)
sortable.Remove(index)
sortable.Insert(index + 1, s)
swapped = True
End If
index = index + 1
Wend
Loop Until Not swapped
'sortable is now sorted
</syntaxhighlight>
 
==={{header|Run BASIC}}===
{{works with|QBasic|1.1}}
{{works with|Just BASIC}}
<syntaxhighlight lang="runbasic">siz = 100
dim data$(siz)
unSorted = 1
 
WHILE unSorted
unSorted = 0
FOR i = 1 TO siz -1
IF data$(i) > data$(i +1) THEN
tmp$ = data$(i)
data$(i) = data$(i +1)
data$(i + 1) = tmp$
unSorted = 1
END IF
NEXT
WEND</syntaxhighlight>
 
==={{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.
<syntaxhighlight lang="basic"> 10 LET S$="FIRE BURN AND CAULDRON BUBBLE"
20 PRINT S$
30 LET L=LEN S$-1
40 LET C=0
50 FOR I=1 TO L
60 IF S$(I)<=S$(I+1) THEN GOTO 120
70 LET T$=S$(I)
80 LET S$(I)=S$(I+1)
90 LET S$(I+1)=T$
100 PRINT AT 0,I-1;S$(I TO I+1)
110 LET C=1
120 NEXT I
130 LET L=L-1
140 IF C THEN GOTO 40</syntaxhighlight>
{{out}}
<pre> AABBBBCDDEEFILLNNNORRRUUU</pre>
 
==={{header|TI-83 BASIC}}===
Input your data into L<sub>1</sub> and run this program to organize it.
:L<sub>1</sub>→L<sub>2</sub>
:1+dim(L<sub>2</sub>)→N
:For(D,1,dim(L<sub>2</sub>))
:N-1→N
:0→I
:For(C,1,dim(L<sub>2</sub>)-2)
:For(A,dim(L<sub>2</sub>)-N+1,dim(L<sub>2</sub>)-1)
:If L<sub>2</sub>(A)&gt;L<sub>2</sub>(A+1)
:Then
:1→I
:L<sub>2</sub>(A)→B
:L<sub>2</sub>(A+1)→L<sub>2</sub>(A)
:B→L<sub>2</sub>(A+1)
:End
:End
:End
:If I=0
:Goto C
:End
:Lbl C
:If L<sub>2</sub>(1)&gt;L<sub>2</sub>(2)
:Then
:L<sub>2</sub>(1)→B
:L<sub>2</sub>(2)→L<sub>2</sub>(1)
:B→L<sub>2</sub>(2)
:End
:DelVar A
:DelVar B
:DelVar C
:DelVar D
:DelVar N
:DelVar I
:Return
 
[[wp:Odd-even sort|Odd-Even Bubble Sort]] (same IO):
:"ODD-EVEN"
:L<sub>1</sub>→L<sub>2</sub>(
:1+dim(L<sub>2</sub>)→N
:For(D,1,dim(L<sub>2</sub>))
:N-1→N
:0→O
:For(C,1,dim(L<sub>2</sub>)-2)
:For(A,dim(L<sub>2</sub>)-N+2,dim(L<sub>2</sub>)-1,2)
:If L<sub>2</sub>(A)>L<sub>2</sub>(A+1)
:Then
:1→O
:L<sub>2</sub>(A)→B
:L<sub>2</sub>(A+1)→L<sub>2</sub>(A)
:B→L<sub>2</sub>(A+1)
:End
:End
:For(A,dim(L<sub>2</sub>)-N+1,dim(L<sub>2</sub>)-1,2)
:If L<sub>2</sub>(A)>L<sub>2</sub>(A+1)
:Then
:1→O
:L<sub>2</sub>(A)→B
:L<sub>2</sub>(A+1)→L<sub>2</sub>(A)
:B→L<sub>2</sub>(A+1)
:End
:End
:End
:If O=0
:Goto C
:End
:Lbl C
:If L<sub>2</sub>(1)>L<sub>2</sub>(2)
:Then
:L<sub>2</sub>(1)→B
:L<sub>2</sub>(2)→L<sub>2</sub>(1)
:B→L<sub>2</sub>(2)
:End
:DelVar A
:DelVar B
:DelVar C
:DelVar D
:DelVar N
:DelVar O
:Return
 
Implementation of the pseudo code given at the top of the page. Place data to be sorted in L<sub>1</sub>
:dim(L<sub>1</sub>)→D
:Repeat C=0
:0→C
:D–1→D
:For(I,1,D)
:If L<sub>1</sub>(I)>L<sub>1</sub>(I+1):Then
:L<sub>1</sub>(I)→C
:L<sub>1</sub>(I+1)→L<sub>1</sub>(I)
:C→L<sub>1</sub>(I+1)
:1→C
:End
:End
:End
:L<sub>1</sub>
 
==={{header|True BASIC}}===
<syntaxhighlight lang="qbasic">OPTION BASE 1
LET size = 10
DIM nums(0)
MAT REDIM nums(size)
RANDOMIZE
PRINT "Before:";
FOR i = 1 TO size
LET nums(i) = INT(RND*100)
PRINT USING " ##": nums(i);
NEXT i
PRINT
 
! Sort
LET counter = size
DO
LET changed = 0
FOR i = 1 TO counter-1
IF nums(i) > nums(i+1) THEN
LET tmp = nums(i)
LET nums(i) = nums(i+1)
LET nums(i+1) = tmp
LET changed = 1
END IF
NEXT i
LET counter = counter-1
LOOP WHILE (changed<>0)
 
! Display result
PRINT "After: ";
FOR i = 1 TO 10
PRINT USING " ##": nums(i);
NEXT i
PRINT
END</syntaxhighlight>
{{out}}
<pre>Similar as QuickBASIC entry.</pre>
 
==={{header|uBasic/4tH}}===
<syntaxhighlight lang="text">PRINT "Bubble sort:"
n = FUNC (_InitArray)
PROC _ShowArray (n)
PROC _Bubblesort (n)
PROC _ShowArray (n)
PRINT
END
_Bubblesort PARAM(1) ' Bubble sort
LOCAL (2)
 
DO
b@ = 0
FOR c@ = 1 TO a@-1
IF @(c@-1) > @(c@) THEN PROC _Swap (c@, c@-1) : b@ = c@
NEXT
DECRa@ total= b@
UNTIL b@ = 0
WEND
LOOP
PRINT t$</lang>
 
RETURN
_Swap PARAM(2) ' Swap two array elements
PUSH @(a@)
@(a@) = @(b@)
@(b@) = POP()
RETURN
_InitArray ' Init example array
PUSH 4, 65, 2, -31, 0, 99, 2, 83, 782, 1
FOR i = 0 TO 9
@(i) = POP()
NEXT
RETURN (i)
_ShowArray PARAM (1) ' Show array subroutine
FOR i = 0 TO a@-1
PRINT @(i),
NEXT
PRINT
RETURN</syntaxhighlight>
 
==={{header|VBA}}===
{{trans|Phix}}<syntaxhighlight lang="vb">Private Function bubble_sort(s As Variant) As Variant
Dim tmp As Variant
Dim changed As Boolean
For j = UBound(s) To 1 Step -1
changed = False
For i = 1 To j - 1
If s(i) > s(i + 1) Then
tmp = s(i)
s(i) = s(i + 1)
s(i + 1) = tmp
changed = True
End If
Next i
If Not changed Then
Exit For
End If
Next j
bubble_sort = s
End Function
Public Sub main()
s = [{4, 15, "delta", 2, -31, 0, "alfa", 19, "gamma", 2, 13, "beta", 782, 1}]
Debug.Print "Before: "
Debug.Print Join(s, ", ")
Debug.Print "After: "
Debug.Print Join(bubble_sort(s), ", ")
End Sub</syntaxhighlight>{{out}}
<pre>Before:
4, 15, delta, 2, -31, 0, alfa, 19, gamma, 2, 13, beta, 782, 1
After:
-31, 0, 1, 2, 2, 4, 13, 15, 19, 782, alfa, beta, delta, gamma</pre>
 
==={{header|VBScript}}===
Doing the decr and incr thing is superfluous, really. I just had stumbled over the byref thing for <code>swap</code> and wanted to see where else it would work.
 
For those unfamiliar with Perth, WA Australia, the five strings being sorted are names of highways.
 
=====Implementation=====
<syntaxhighlight lang="vb">
sub decr( byref n )
n = n - 1
end sub
 
sub incr( byref n )
n = n + 1
end sub
 
sub swap( byref a, byref b)
dim tmp
tmp = a
a = b
b = tmp
end sub
 
function bubbleSort( a )
dim changed
dim itemCount
itemCount = ubound(a)
do
changed = false
decr itemCount
for i = 0 to itemCount
if a(i) > a(i+1) then
swap a(i), a(i+1)
changed = true
end if
next
loop until not changed
bubbleSort = a
end function
</syntaxhighlight>
 
=====Invocation=====
<syntaxhighlight lang="vb">
dim a
a = array( "great eastern", "roe", "stirling", "albany", "leach")
wscript.echo join(a,", ")
bubbleSort a
wscript.echo join(a,", ")
</syntaxhighlight>
 
{{out}}
<pre>
<pre>Amsterdam Bern Bonn Kiev Lima Madrid Moscow Paris Rome Vienna Warschau</pre>
great eastern, roe, stirling, albany, leach
albany, great eastern, leach, roe, stirling
</pre>
 
==={{header|Visual Basic .NET}}===
'''Platform:''' [[.NET]]
 
{{works with|Visual Basic .NET|9.0+}}
<syntaxhighlight lang="vbnet">Do Until NoMoreSwaps = True
NoMoreSwaps = True
For Counter = 1 To (NumberOfItems - 1)
If List(Counter) > List(Counter + 1) Then
NoMoreSwaps = False
Temp = List(Counter)
List(Counter) = List(Counter + 1)
List(Counter + 1) = Temp
End If
Next
NumberOfItems = NumberOfItems - 1
Loop</syntaxhighlight>
 
==={{header|Yabasic}}===
<syntaxhighlight lang="yabasic">// Animated sort.
// Original idea by William Tang, obtained from MicroHobby 25 Years (https://microhobby.speccy.cz/zxsf/MH-25Years.pdf)
 
clear screen
 
n=15 : m=18 : y=9 : t$=chr$(17)+chr$(205)+chr$(205)
dim p(n), p$(n)
 
for x=1 TO n
p(x)=ran(15)+1
p$(x)=str$(p(x),"##.######")
print at(0,x) p$(x)
next x
 
for j=1 to n-1
for i=j+1 to n
l=n+j-i+1
if p(j) > p(l) then
print color("yellow","red") at(0,j) p$(j)
if l<>m then
for x=m to l step sig(l-m): print at(18,x) t$ : print at (18,x+sig(m-l)) " " : pause .02 : next x
end if
for x=17 TO y step -1 : print at(x,l) t$+" " : pause .02 : next x
for x=0 TO 10 : print at(x,l) " "+p$(l)+t$ : pause .02 : next x
for x=l TO j STEP -1 : print at(11,x) p$(l)+t$ : print at(11,x+1) " " : pause .02 : next x
print at(0,j) " "
for x=j+1 TO l-1 : print color("yellow","red") at(0,x) p$(j) : pause .02 : print at(0,x) p$(x) : pause .02 : next x
print at(0,l) p$(j)
for x=10 TO 0 step -1 : print at(x,j) p$(l)+t$+" " : pause .02 : next x
for x=y TO 17 : print at(x,j) " "+t$ : pause .02 : next x
m=j
t=p(l) : tem$=p$(l)
p(l)=p(j) : p$(l)=p$(j)
p(j)=t : p$(j)=tem$
end if
pause .02
next i
next j
 
for x=m TO 18 : print at(18,x-1) " " : print at(18,x) t$ : pause .02 : next x
</syntaxhighlight>
 
==={{header|ZX Spectrum Basic}}===
<syntaxhighlight lang="zxbasic">5000 CLS
5002 LET a$="": FOR f=1 TO 64: LET a$=a$+CHR$ (32+INT (RND*96)): NEXT f
5004 PRINT a$; AT 10,0;"ZigZag BubbleSORT"
5010 LET la=LEN a$
5011 LET i=1: LET u=0
5020 LET d=0: LET p=(u=0)-(u=1)
5021 LET l=(i AND u=0)+(la-i+u AND u=1)
5030 IF u=0 THEN IF a$(l+1)>=a$(l) THEN GO TO 5050
5031 IF u=1 THEN IF a$(l-1)<=a$(l) THEN GO TO 5050
5040 LET d=1
5042 LET t$=a$(l+p)
5043 LET a$(l+p)=a$(l)
5044 LET a$(l)=t$
5050 LET l=l+p
5051 PRINT AT 10,21;a$(l);AT 12,0;a$
5055 IF l<=la-i AND l>=i THEN GO TO 5023
5061 LET i=i+NOT u
5063 LET u=NOT u
5064 IF d AND i<la THEN GO TO 5020
5072 PRINT AT 12,0;a$
9000 STOP </syntaxhighlight>
 
The traditional solution:
 
<syntaxhighlight lang="zxbasic"> 10 LET siz=32
20 DIM d$(siz)
30 REM Populate d$
40 FOR n=1 TO siz: LET d$(n)=CHR$ (48+INT (RND*75)): NEXT n
50 PRINT d$
60 LET unSorted=0
70 FOR i=1 TO siz-1
80 IF d$(i)>d$(i+1) THEN LET t$=d$(i): LET d$(i)=d$(i+1): LET d$(i+1)=t$: LET unSorted=1
90 NEXT i
100 IF unSorted THEN LET siz=siz-1: GO TO 60
110 PRINT d$</syntaxhighlight>
 
=={{header|BCPL}}==
<langsyntaxhighlight lang="bcpl">get "libhdr"
 
let bubblesort(v, length) be
Line 1,425 ⟶ 2,445:
for i=0 to 9 do writef("%N ", v!i)
wrch('*N')
$)</langsyntaxhighlight>
{{out}}
<pre>1 2 3 4 5 6 7 8 9 10</pre>
 
=={{header|Befunge}}==
 
<syntaxhighlight lang="befunge">
000p&: v >20g:7g\1+7g2v
v00p7g00 _10p0>20p20g:7g\1+7g`|0p7+1g02p7g0<
>g1+00p&:^ |-\g00:+1g02 <
0 >$10gv
|-\g00:+1 <
>1->:7g\:#v_$>:#._25*,@
^ <
</syntaxhighlight>
 
=={{header|C}}==
<langsyntaxhighlight lang="c">#include <stdio.h>
 
void bubble_sort (int *a, int n) {
Line 1,459 ⟶ 2,491:
return 0;
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,468 ⟶ 2,500:
=={{header|C sharp|C#}}==
{{works with|C sharp|C#|3.0+}}
<langsyntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
 
Line 1,511 ⟶ 2,543:
}
}
}</langsyntaxhighlight>
 
=={{header|C++}}==
Uses C++11. Compile with
g++ -std=c++11 bubble.cpp
<langsyntaxhighlight lang="cpp">#include <algorithm>
#include <iostream>
#include <iterator>
Line 1,539 ⟶ 2,571:
copy(std::begin(a), std::end(a), std::ostream_iterator<int>(std::cout, " "));
std::cout << "\n";
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,548 ⟶ 2,580:
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.
<langsyntaxhighlight lang="clojure">(ns bubblesort
(:import java.util.ArrayList))
Line 1,574 ⟶ 2,606:
arr)))
 
(println (bubble-sort (ArrayList. [10 9 8 7 6 5 4 3 2 1])))</langsyntaxhighlight>
 
Purely functional version working on Clojure sequences:
<langsyntaxhighlight lang="clojure">(defn- bubble-step
"was-changed: whether any elements prior to the current first element
were swapped;
Line 1,603 ⟶ 2,635:
(recur less? result)))))
(println (bubble-sort [10 9 8 7 6 5 4 3 2 1]))</langsyntaxhighlight>
 
=={{header|CLU}}==
<langsyntaxhighlight lang="clu">% Bubble-sort an array in place.
bubble_sort = proc [T: type] (a: array[T])
where T has lt: proctype (T,T) returns (bool)
Line 1,641 ⟶ 2,673:
bubble_sort[int](test)
stream$puts(po, "After: ") print_arr[int](test, 3, po)
end start_up</langsyntaxhighlight>
{{out}}
<pre>Before: 7 -5 0 2 99 16 4 20 47 19
Line 1,649 ⟶ 2,681:
Only for lists of integers.
 
<langsyntaxhighlight lang="cmake"># bubble_sort(var [value1 value2...]) sorts a list of integers.
function(bubble_sort var)
math(EXPR last "${ARGC} - 1") # Prepare to sort ARGV[1]..ARGV[last].
Line 1,674 ⟶ 2,706:
endforeach(index)
set("${var}" "${answer}" PARENT_SCOPE)
endfunction(bubble_sort)</langsyntaxhighlight>
 
<langsyntaxhighlight lang="cmake">bubble_sort(result 33 11 44 22 66 55)
message(STATUS "${result}")</langsyntaxhighlight>
 
<pre>-- 11;22;33;44;55;66</pre>
Line 1,684 ⟶ 2,716:
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.
<langsyntaxhighlight lang="cobol">
IDENTIFICATION DIVISION.
PROGRAM-ID. BUBBLESORT.
Line 1,830 ⟶ 2,862:
F-999.
EXIT.
</syntaxhighlight>
</lang>
 
A more modern version of COBOL.
<langsyntaxhighlight lang="cobol">
identification division.
program-id. BUBBLSRT.
Line 1,888 ⟶ 2,920:
end-perform
.
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,895 ⟶ 2,927:
=={{header|Common Lisp}}==
Bubble sort an sequence in-place, using the < operator for comparison if no comaprison function is provided
<langsyntaxhighlight lang="lisp">(defun bubble-sort (sequence &optional (compare #'<))
"sort a sequence (array or list) with an optional comparison function (cl:< is the default)"
(loop with sorted = nil until sorted do
Line 1,904 ⟶ 2,936:
(rotatef (elt sequence a)
(elt sequence (1+ a)))
(setf sorted nil)))))</langsyntaxhighlight>
 
<langsyntaxhighlight lang="lisp">(bubble-sort (list 5 4 3 2 1))</langsyntaxhighlight>
 
<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.
 
<langsyntaxhighlight lang="lisp">(defun bubble-sort-vector (vector predicate &aux (len (1- (length vector))))
(do ((swapped t)) ((not swapped) vector)
(setf swapped nil)
Line 1,929 ⟶ 2,961:
(etypecase sequence
(list (bubble-sort-list sequence predicate))
(vector (bubble-sort-vector sequence predicate))))</langsyntaxhighlight>
 
=={{header|Cowgol}}==
 
<langsyntaxhighlight lang="cowgol">include "cowgol.coh";
 
# Comparator interface, on the model of C, i.e:
Line 1,987 ⟶ 3,019:
i := i + 1;
end loop;
print_nl();</langsyntaxhighlight>
 
{{out}}
Line 1,994 ⟶ 3,026:
 
=={{header|D}}==
<langsyntaxhighlight lang="d">import std.stdio, std.algorithm : swap;
 
T[] bubbleSort(T)(T[] data) pure nothrow
Line 2,017 ⟶ 3,049:
auto array = [28, 44, 46, 24, 19, 2, 17, 11, 25, 4];
writeln(array.bubbleSort());
}</langsyntaxhighlight>
{{out}}
<pre>[2, 4, 11, 17, 19, 24, 25, 28, 44, 46]</pre>
Line 2,047 ⟶ 3,079:
 
Static array is an arbitrary-based array of fixed length
<langsyntaxhighlight Delphilang="delphi">program TestBubbleSort;
 
{$APPTYPE CONSOLE}
Line 2,100 ⟶ 3,132:
Writeln;
Readln;
end.</langsyntaxhighlight>
{{out}}
<pre>
Line 2,106 ⟶ 3,138:
0 3 5 7 8 16 20 27 29 31 37 42 47 67 84 86
</pre>
 
=={{header|Draco}}==
<syntaxhighlight lang="draco">/* Bubble sort an array of integers */
proc nonrec bubblesort([*] int a) void:
bool sorted;
int i, temp;
sorted := false;
while not sorted do
sorted := true;
for i from 1 upto dim(a,1)-1 do
if a[i-1] > a[i] then
sorted := false;
temp := a[i-1];
a[i-1] := a[i];
a[i] := temp
fi
od
od
corp
 
/* Test */
proc nonrec main() void:
int i;
[10] int a = (9, -5, 3, 3, 24, -16, 3, -120, 250, 17);
write("Before sorting: ");
for i from 0 upto 9 do write(a[i]:5) od;
writeln();
bubblesort(a);
write("After sorting: ");
for i from 0 upto 9 do write(a[i]:5) od
corp</syntaxhighlight>
{{out}}
<pre>Before sorting: 9 -5 3 3 24 -16 3 -120 250 17
After sorting: -120 -16 -5 3 3 3 9 17 24 250</pre>
 
=={{header|Dyalect}}==
 
<langsyntaxhighlight lang="dyalect">func bubbleSort(list) {
var done = false
while !done {
done = true
for i in 1..(list.lenLength()-1) {
if list[i - 1] > list[i] {
var x = list[i]
Line 2,123 ⟶ 3,191:
}
}
 
var xs = [3,1,5,4,2,6]
bubbleSort(xs)
print(xs)</langsyntaxhighlight>
 
{{out}}
Line 2,133 ⟶ 3,201:
 
=={{header|E}}==
<langsyntaxhighlight lang="e">def bubbleSort(target) {
__loop(fn {
var changed := false
Line 2,145 ⟶ 3,213:
changed
})
}</langsyntaxhighlight>
 
(Uses the primitive __loop directly because it happens to map to the termination test for this algorithm well.)
 
=={{header|EasyLang}}==
<syntaxhighlight lang="easylang">
proc bubbleSort . a[] .
repeat
changed = 0
for i = 1 to len a[] - 1
if a[i] > a[i + 1]
swap a[i] a[i + 1]
changed = 1
.
.
until changed = 0
.
.
array[] = [ 5 1 19 25 12 1 14 7 ]
bubbleSort array[]
print array[]
</syntaxhighlight>
{{out}}
<pre>[ 1 1 5 7 12 14 19 25 ]</pre>
 
=={{header|EchoLisp}}==
<langsyntaxhighlight lang="scheme">
;; sorts a vector of objects in place
;; proc is an user defined comparison procedure
Line 2,167 ⟶ 3,256:
(bubble-sort V sort/length)
→ #(zen simon elvis albert antoinette)
</syntaxhighlight>
</lang>
 
=={{header|EDSAC order code}}==
Line 2,176 ⟶ 3,265:
 
To clarify the EDSAC program, an equivalent Pascal program is added as a comment.
<langsyntaxhighlight lang="edsac">
[Bubble sort demo for Rosetta Code website]
[EDSAC program. Initial Orders 2]
Line 2,328 ⟶ 3,417:
E 14 Z [define entry point]
P F [acc = 0 on entry]
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,348 ⟶ 3,437:
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.
 
<langsyntaxhighlight lang="eiffel">class
APPLICATION
create
Line 2,377 ⟶ 3,466:
my_set: MY_SORTED_SET [INTEGER]
-- Set to be sorted
end</langsyntaxhighlight>
 
The second class is <code lang="eiffel">MY_SORTED_SET</code>.
 
<langsyntaxhighlight lang="eiffel">class
MY_SORTED_SET [G -> COMPARABLE]
inherit
Line 2,416 ⟶ 3,505:
end
end
end</langsyntaxhighlight>
 
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,436 ⟶ 3,525:
=={{header|Elena}}==
{{trans|C#}}
ELENA 56.0x :
<langsyntaxhighlight lang="elena">import system'routines;
import extensions;
Line 2,452 ⟶ 3,541:
madeChanges := false;
itemCount -= 1;
for(int i := 0,; i < itemCount,; i += 1)
{
if (list[i] > list[i + 1])
Line 2,470 ⟶ 3,559:
var list := new int[]{3, 7, 3, 2, 1, -4, 10, 12, 4};
console.printLine(list.bubbleSort().asEnumerable())
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,477 ⟶ 3,566:
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">defmodule Sort do
def bsort(list) when is_list(list) do
t = bsort_iter(list)
Line 2,487 ⟶ 3,576:
def bsort_iter([x, y | t]), do: [x | bsort_iter([y | t])]
def bsort_iter(list), do: list
end</langsyntaxhighlight>
 
=={{header|Erlang}}==
sort/3 copied from Stackoverflow.
<syntaxhighlight lang="erlang">
<lang Erlang>
-module( bubble_sort ).
 
Line 2,508 ⟶ 3,597:
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 ).
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,516 ⟶ 3,605:
 
=={{header|ERRE}}==
<syntaxhighlight lang="erre">
<lang ERRE>
PROGRAM BUBBLE_SORT
 
Line 2,548 ⟶ 3,637:
PRINT
END PROGRAM
</syntaxhighlight>
</lang>
 
=={{header|Euphoria}}==
<langsyntaxhighlight lang="euphoria">function bubble_sort(sequence s)
object tmp
integer changed
Line 2,577 ⟶ 3,666:
pretty_print(1,s,{2})
puts(1,"\nAfter: ")
pretty_print(1,bubble_sort(s),{2})</langsyntaxhighlight>
 
{{out}}
Line 2,614 ⟶ 3,703:
 
=={{header|Ezhil}}==
<syntaxhighlight lang="ezhil">
<lang Ezhil>
 
## இந்த நிரல் ஒரு பட்டியலில் உள்ள எண்களை Bubble Sort என்ற முறைப்படி ஏறுவரிசையிலும் பின்னர் அதையே இறங்குவரிசையிலும் அடுக்கித் தரும்
Line 2,682 ⟶ 3,771:
பதிப்பி எண்கள்பிரதி
 
</syntaxhighlight>
</lang>
 
=={{header|F Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">let BubbleSort (lst : list<int>) =
let rec sort accum rev lst =
match lst, rev with
Line 2,693 ⟶ 3,782:
| head::tail, _ -> sort (head::accum) rev tail
sort [] true lst
</syntaxhighlight>
</lang>
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">USING: fry kernel locals math math.order sequences
sequences.private ;
IN: rosetta.bubble
Line 2,718 ⟶ 3,807:
 
: natural-sort! ( seq -- )
[ <=> ] sort! ;</langsyntaxhighlight>
 
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.
 
<langsyntaxhighlight lang="factor">10 [ 10000 random ] replicate
[ "Before: " write . ]
[ "Natural: " write [ natural-sort! ] keep . ]
[ "Reverse: " write [ [ >=< ] sort! ] keep . ] tri</langsyntaxhighlight>
 
Before: { 3707 5045 4661 1489 3140 7195 8844 6506 6322 3199 }
Line 2,734 ⟶ 3,823:
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.
 
<langsyntaxhighlight lang="fish">v Sorts the (pre-loaded) stack
with bubblesort.
v <
Line 2,741 ⟶ 3,830:
>~{ao ^
>~}l &{ v
o","{n:&-1^?=0:&<</langsyntaxhighlight>
 
=={{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.
 
<langsyntaxhighlight lang="forth">defer bubble-test
' > is bubble-test
 
Line 2,754 ⟶ 3,843:
i 2@ bubble-test if i 2@ swap i 2! then
cell +loop
loop ;</langsyntaxhighlight>
 
This is the same algorithm done without the local variables:
 
<langsyntaxhighlight lang="forth">: bubble ( addr cnt -- )
dup 1 do
2dup i - cells bounds do
i 2@ bubble-test if i 2@ swap i 2! then
cell +loop
loop ;</langsyntaxhighlight>
 
Version with ''O(n)'' best case:
<langsyntaxhighlight lang="forth">: bubble ( addr len -- )
begin
1- 2dup true -rot ( sorted addr len-1 )
Line 2,775 ⟶ 3,864:
then
cell +loop ( sorted )
until 2drop ;</langsyntaxhighlight>
 
Test any version with this:
Line 2,791 ⟶ 3,880:
 
=={{header|Fortran}}==
<langsyntaxhighlight lang="fortran">SUBROUTINE Bubble_Sort(a)
REAL, INTENT(in out), DIMENSION(:) :: a
REAL :: temp
Line 2,809 ⟶ 3,898:
IF (.NOT. swapped) EXIT
END DO
END SUBROUTINE Bubble_Sort</langsyntaxhighlight>
 
=={{header|FreeBASIC}}==
Per task pseudo code:
<lang FreeBASIC>' version 21-10-2016
' compile with: fbc -s console
' for boundry checks on array's compile with: fbc -s console -exx
 
Sub bubblesort(bs() As Long)
' sort from lower bound to the highter bound
' array's can have subscript range from -2147483648 to +2147483647
Dim As Long lb = LBound(bs)
Dim As Long ub = UBound(bs)
Dim As Long done, i
 
Do
done = 0
For i = lb To ub -1
' replace "<" with ">" for downwards sort
If bs(i) > bs(i +1) Then
Swap bs(i), bs(i +1)
done = 1
End If
Next
Loop Until done = 0
 
End Sub
 
' ------=< MAIN >=------
 
Dim As Long i, array(-7 To 7)
 
Dim As Long a = LBound(array), b = UBound(array)
 
Randomize Timer
For i = a To b : array(i) = i : Next
For i = a To b ' little shuffle
Swap array(i), array(Int(Rnd * (b - a +1)) + a)
Next
 
Print "unsort ";
For i = a To b : Print Using "####"; array(i); : Next : Print
bubblesort(array()) ' sort the array
Print " sort ";
For i = a To b : Print Using "####"; array(i); : Next : Print
 
' empty keyboard buffer
While InKey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End</lang>
{{out}}
<pre>unsort -7 3 -4 -6 4 -1 -2 2 7 0 5 1 -3 -5 6
sort -7 -6 -5 -4 -3 -2 -1 0 1 2 3 4 5 6 7</pre>
 
=={{header|g-fu}}==
<langsyntaxhighlight lang="g-fu">
(fun bubbles (vs)
(let done? F n (len vs))
Line 2,881 ⟶ 3,917:
---
(1 2 3)
</syntaxhighlight>
</lang>
 
=={{header|GambasGDScript}}==
Here is an implementation of Bubble Sort algorithm in GDScript for array of primitive types:
'''[https://gambas-playground.proko.eu/?gist=ba84832d633cb92bbe6c2f54704819c3 Click this link to run this code]'''
<syntaxhighlight lang="gdscript">
<lang gambas>Public Sub Main()
extends Node2D
Dim byToSort As Byte[] = [249, 28, 111, 36, 171, 98, 29, 448, 44, 147, 154, 46, 102, 183, 24,
120, 19, 123, 2, 17, 226, 11, 211, 25, 191, 205, 77]
Dim byCount As Byte
Dim bSorting As Boolean
 
Print "To sort: -"
ShowWorking(byToSort)
Print
Repeat
bSorting = False
For byCount = 0 To byToSort.Max - 1
If byToSort[byCount] > byToSort[byCount + 1] Then
Swap byToSort[byCount], byToSort[byCount + 1]
bSorting = True
Endif
Next
If bSorting Then ShowWorking(byToSort)
Until bSorting = False
End
'-----------------------------------------
Public Sub ShowWorking(byToSort As Byte[])
Dim byCount As Byte
 
func BubbleSort(_array : Array) -> void:
For byCount = 0 To byToSort.Max
for i in range(_array.size() - 1):
Print Str(byToSort[byCount]);
var swapped : bool = false
If byCount <> byToSort.Max Then Print ",";
for j in range(_array.size() - i - 1):
Next
if _array[j] > _array[j + 1]:
var tmp = _array[j]
_array[j] = _array[j + 1]
_array[j + 1] = tmp
swapped = true
if not swapped:
break
return
 
Print
 
func _ready() -> void:
End</lang>
var array : Array = range(-10, 10)
Output:
array.shuffle()
 
print("Initial array:")
print(array)
 
BubbleSort(array)
 
print("Sorted array:")
print(array)
return
</syntaxhighlight>
 
Possible output:
{{out}}
<pre>
Initial array:
To sort: -
[-7, -6, 2, -8, 4, -1, -3, -5, 5, -10, -4, 7, 3, 8, 0, -9, 6, 9, -2, 1]
249,28,111,36,171,98,29,192,44,147,154,46,102,183,24,120,19,123,2,17,226,11,211,25,191,205,77
Sorted array:
[-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
</pre>
 
If you need to sort objects, this can be done in way like this:
<syntaxhighlight lang="gdscript">
class Comparable:
var Value
 
func _init(_val):
self.Value = _val
 
func compare(_other : Comparable) -> int:
# Here is the simple implementation of compare
# for primitive type wrapper.
return self.Value - _other.Value
 
 
func BubbleSortObjects(_array : Array) -> void:
28,111,36,171,98,29,192,44,147,154,46,102,183,24,120,19,123,2,17,226,11,211,25,191,205,77,249
for i in range(_array.size() - 1):
28,36,111,98,29,171,44,147,154,46,102,183,24,120,19,123,2,17,192,11,211,25,191,205,77,226,249
var swapped : bool = false
28,36,98,29,111,44,147,154,46,102,171,24,120,19,123,2,17,183,11,192,25,191,205,77,211,226,249
for j in range(_array.size() - i - 1):
28,36,29,98,44,111,147,46,102,154,24,120,19,123,2,17,171,11,183,25,191,192,77,205,211,226,249
if _array[j].compare(_array[j + 1]) > 0:
28,29,36,44,98,111,46,102,147,24,120,19,123,2,17,154,11,171,25,183,191,77,192,205,211,226,249
var tmp = _array[j]
28,29,36,44,98,46,102,111,24,120,19,123,2,17,147,11,154,25,171,183,77,191,192,205,211,226,249
_array[j] = _array[j + 1]
28,29,36,44,46,98,102,24,111,19,120,2,17,123,11,147,25,154,171,77,183,191,192,205,211,226,249
_array[j + 1] = tmp
28,29,36,44,46,98,24,102,19,111,2,17,120,11,123,25,147,154,77,171,183,191,192,205,211,226,249
swapped = true
28,29,36,44,46,24,98,19,102,2,17,111,11,120,25,123,147,77,154,171,183,191,192,205,211,226,249
if not swapped:
28,29,36,44,24,46,19,98,2,17,102,11,111,25,120,123,77,147,154,171,183,191,192,205,211,226,249
break
28,29,36,24,44,19,46,2,17,98,11,102,25,111,120,77,123,147,154,171,183,191,192,205,211,226,249
return
28,29,24,36,19,44,2,17,46,11,98,25,102,111,77,120,123,147,154,171,183,191,192,205,211,226,249
 
28,24,29,19,36,2,17,44,11,46,25,98,102,77,111,120,123,147,154,171,183,191,192,205,211,226,249
</syntaxhighlight>
24,28,19,29,2,17,36,11,44,25,46,98,77,102,111,120,123,147,154,171,183,191,192,205,211,226,249
24,19,28,2,17,29,11,36,25,44,46,77,98,102,111,120,123,147,154,171,183,191,192,205,211,226,249
This approach is slow though. To sort array of primitive types use Array.sort() method instead.
19,24,2,17,28,11,29,25,36,44,46,77,98,102,111,120,123,147,154,171,183,191,192,205,211,226,249
To sort array of objects you can use Array.sort_custom(func : Callable) method.
19,2,17,24,11,28,25,29,36,44,46,77,98,102,111,120,123,147,154,171,183,191,192,205,211,226,249
2,17,19,11,24,25,28,29,36,44,46,77,98,102,111,120,123,147,154,171,183,191,192,205,211,226,249
2,17,11,19,24,25,28,29,36,44,46,77,98,102,111,120,123,147,154,171,183,191,192,205,211,226,249
2,11,17,19,24,25,28,29,36,44,46,77,98,102,111,120,123,147,154,171,183,191,192,205,211,226,249
</pre>
 
=={{header|Go}}==
Per task pseudocode:
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 2,971 ⟶ 4,021:
}
}
}</langsyntaxhighlight>
 
More generic version that can sort anything that implements <code>sort.Interface</code>:
<langsyntaxhighlight lang="go">package main
 
import (
Line 3,002 ⟶ 4,052:
}
}
}</langsyntaxhighlight>
 
=={{header|Groovy}}==
Solution:
<langsyntaxhighlight 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) } }
Line 3,014 ⟶ 4,064:
while (swapped) { swapped = (1..<list.size()).any { checkSwap(list, it-1) } }
list
}</langsyntaxhighlight>
 
Test Program:
<langsyntaxhighlight 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])</langsyntaxhighlight>
 
{{out}}
Line 3,026 ⟶ 4,076:
=={{header|Haskell}}==
This version checks for changes in a separate step for simplicity, because Haskell has no variables to track them with.
<langsyntaxhighlight lang="haskell">bsort :: Ord a => [a] -> [a]
bsort s = case _bsort s of
t | t == s -> t
Line 3,032 ⟶ 4,082:
where _bsort (x:x2:xs) | x > x2 = x2:(_bsort (x:xs))
| otherwise = x:(_bsort (x2:xs))
_bsort s = s</langsyntaxhighlight>
 
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.
 
<langsyntaxhighlight lang="haskell">import Data.Maybe (fromMaybe)
import Control.Monad
 
Line 3,044 ⟶ 4,094:
then Just $ x2 : fromMaybe (x:xs) (_bsort $ x:xs)
else liftM (x:) $ _bsort (x2:xs)
_bsort _ = Nothing</langsyntaxhighlight>
 
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 (>).
 
<langsyntaxhighlight lang="haskell">import Data.Maybe (fromMaybe)
import Control.Monad
 
Line 3,063 ⟶ 4,113:
 
bsort :: Ord a => [a] -> [a]
bsort = bubbleSortBy (<)</langsyntaxhighlight>
 
=={{header|Haxe}}==
<langsyntaxhighlight lang="haxe">class BubbleSort {
@:generic
public static function sort<T>(arr:Array<T>) {
Line 3,104 ⟶ 4,154:
Sys.println('Sorted Strings: ' + stringArray);
}
}</langsyntaxhighlight>
 
{{out}}
Line 3,117 ⟶ 4,167:
 
=={{header|HicEst}}==
<langsyntaxhighlight lang="fortran">SUBROUTINE Bubble_Sort(a)
REAL :: a(1)
Line 3,132 ⟶ 4,182:
IF (swapped == 0) RETURN
ENDDO
END</langsyntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
Icon/Unicon implementation of a bubble sort
<langsyntaxhighlight Iconlang="icon">procedure main() #: demonstrate various ways to sort a list and string
demosort(bubblesort,[3, 14, 1, 5, 9, 2, 6, 3],"qwerty")
end
Line 3,151 ⟶ 4,201:
X[i-1] :=: X[swapped := i]
return X
end</langsyntaxhighlight>
 
{{out}}
Line 3,171 ⟶ 4,221:
* 'demosort' can apply different sorting procedures and operators to lists and strings to show how this works. The routines 'displaysort' and 'writex' are helpers.
 
<langsyntaxhighlight lang="icon">invocable all # for op
 
procedure sortop(op,X) #: select how to sort
Line 3,229 ⟶ 4,279:
write()
return
end</langsyntaxhighlight>
 
=={{header|Io}}==
<syntaxhighlight lang="io">
<lang Io>
List do(
bubblesort := method(
Line 3,248 ⟶ 4,298:
)
)
</syntaxhighlight>
</lang>
 
=={{header|J}}==
{{eff note|J|/:~ list}}
<langsyntaxhighlight lang="j">bubbleSort=: (([ (<. , >.) {.@]) , }.@])/^:_</langsyntaxhighlight>
 
Test program:
 
<langsyntaxhighlight lang="j"> ?. 10 $ 10
4 6 8 6 5 8 6 6 6 9
bubbleSort ?. 10 $ 10
4 5 6 6 6 6 6 8 8 9</langsyntaxhighlight>
 
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|Jakt}}==
<syntaxhighlight lang="jakt">
fn bubble_sort<T>(anon mut array: [T]) {
mut item_count = array.size()
mut has_changed = true
while item_count > 1 and has_changed {
has_changed = true
item_count--
for i in 0..item_count {
if array[i] > array[i + 1] {
let temp = array[i]
array[i] = array[i + 1]
array[i + 1] = temp
has_changed = true
}
}
}
}
 
 
fn main() {
mut array = [7, 8, 9, 6, 5, 3, 1, 10, 4, 2]
println("{}", array)
bubble_sort(array)
println("{}", array)
}
</syntaxhighlight>
 
=={{header|Janet}}==
<langsyntaxhighlight lang="janet">
(defn bubble-sort!
[arr]
Line 3,290 ⟶ 4,368:
 
)
</syntaxhighlight>
</lang>
 
=={{header|Java}}==
Bubble sorting (ascending) an array of any <tt>Comparable</tt> type:
<langsyntaxhighlight lang="java">public static <E extends Comparable<? super E>> void bubbleSort(E[] comparable) {
boolean changed = false;
do {
Line 3,307 ⟶ 4,385:
}
} while (changed);
}</langsyntaxhighlight>
 
For descending, simply switch the direction of comparison:
<langsyntaxhighlight lang="java">if (comparable[a].compareTo(comparable[b]) < 0){
//same swap code as before
}</langsyntaxhighlight>
 
=={{header|JavaScript}}==
<langsyntaxhighlight lang="javascript">Array.prototype.bubblesort = function() {
var done = false;
while (!done) {
Line 3,327 ⟶ 4,405:
}
return this;
}</langsyntaxhighlight>
 
{{works with|SEE|3.0}}
{{works with|OSSP js|1.6.20070208}}
<langsyntaxhighlight lang="javascript">Array.prototype.bubblesort = function() {
var done = false;
while (! done) {
Line 3,345 ⟶ 4,423:
}
return this;
}</langsyntaxhighlight>
 
Example:
<langsyntaxhighlight lang="javascript">var my_arr = ["G", "F", "C", "A", "B", "E", "D"];
my_arr.bubblesort();
print(my_arr);</langsyntaxhighlight>
 
{{out}}
Line 3,358 ⟶ 4,436:
 
webpage version (for the rest of us):
<langsyntaxhighlight lang="javascript"><script>
Array.prototype.bubblesort = function() {
var done = false;
Line 3,380 ⟶ 4,458:
}
document.write(output);
</script></langsyntaxhighlight>
 
=={{header|jq}}==
<langsyntaxhighlight lang="jq">def bubble_sort:
def swap(i;j): .[i] as $x | .[i]=.[j] | .[j]=$x;
 
Line 3,396 ⟶ 4,474:
else .
end )
end ) | .[1] ;</langsyntaxhighlight>
'''Example''':
<langsyntaxhighlight lang="jq">(
[3,2,1],
[1,2,3],
["G", "F", "C", "A", "B", "E", "D"]
) | bubble_sort</langsyntaxhighlight>
{{Out}}
<langsyntaxhighlight lang="sh">$ jq -c -n -f Bubble_sort.jq
[1,2,3]
[1,2,3]
["A","B","C","D","E","F","G"]</langsyntaxhighlight>
 
=={{header|Julia}}==
{{works with|Julia|0.6}}
 
<langsyntaxhighlight lang="julia">function bubblesort!(arr::AbstractVector)
for _ in 2:length(arr), j in 1:length(arr)-1
if arr[j] > arr[j+1]
Line 3,422 ⟶ 4,500:
 
v = rand(-10:10, 10)
println("# unordered: $v\n -> ordered: ", bubblesort!(v))</langsyntaxhighlight>
 
{{out}}
Line 3,431 ⟶ 4,509:
{{trans|Java}}
 
<langsyntaxhighlight lang="scala">import java.util.Comparator
 
fun <T> bubbleSort(a: Array<T>, c: Comparator<T>) {
Line 3,446 ⟶ 4,524:
}
} while (changed)
}</langsyntaxhighlight>
 
=={{header|Lambdatalk}}==
<langsyntaxhighlight lang="scheme">
{def bubblesort
{def bubblesort.swap!
Line 3,474 ⟶ 4,552:
{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]
</syntaxhighlight>
</lang>
 
=={{header|Liberty BASIC}}==
<lang lb>
itemCount = 20
dim item(itemCount)
for i = 1 to itemCount
item(i) = int(rnd(1) * 100)
next i
print "Before Sort"
for i = 1 to itemCount
print item(i)
next i
print: print
counter = itemCount
do
hasChanged = 0
for i = 1 to counter - 1
if item(i) > item(i + 1) then
temp = item(i)
item(i) = item(i + 1)
item(i + 1) = temp
hasChanged = 1
end if
next i
counter =counter -1
loop while hasChanged = 1
print "After Sort"
for i = 1 to itemCount
print item(i)
next i
end
</lang>
 
=={{header|Lisaac}}==
<langsyntaxhighlight Lisaaclang="lisaac">Section Header
 
+ name := BUBBLE_SORT;
Line 3,551 ⟶ 4,597:
};
}.do_while {!sorted};
);</langsyntaxhighlight>
 
=={{header|Lua}}==
 
<syntaxhighlight lang="lua">
<lang Lua>
function bubbleSort(A)
local itemCount=#A
Line 3,570 ⟶ 4,616:
until hasChanged == false
end
</syntaxhighlight>
</lang>
 
Example:
<langsyntaxhighlight lang="lua">
list = { 5, 6, 1, 2, 9, 14, 2, 15, 6, 7, 8, 97 }
bubbleSort(list)
Line 3,579 ⟶ 4,625:
print(j)
end
</syntaxhighlight>
</lang>
 
=={{header|Lucid}}==
[http://i.csc.uvic.ca/home/hei/lup/06.html]
<langsyntaxhighlight lang="lucid">bsort(a) = if iseod(first a) then a else
follow(bsort(allbutlast(b)),last(b)) fi
where
Line 3,598 ⟶ 4,644:
last(x) = (x asa iseod next x) fby eod;
allbutlast(x) = if not iseod(next x) then x else eod fi;
end</langsyntaxhighlight>
 
=={{header|M2000 Interpreter}}==
Line 3,606 ⟶ 4,652:
 
 
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module Bubble {
function bubblesort {
Line 3,651 ⟶ 4,697:
}
Bubble
</syntaxhighlight>
</lang>
 
=={{header|M4}}==
<langsyntaxhighlight M4lang="m4">divert(-1)
 
define(`randSeed',141592653)
Line 3,698 ⟶ 4,744:
show(`a')
bubblesort(`a')
show(`a')</langsyntaxhighlight>
 
{{out}}
Line 3,706 ⟶ 4,752:
 
=={{header|Maple}}==
<syntaxhighlight lang="text">arr := Array([17,3,72,0,36,2,3,8,40,0]):
len := numelems(arr):
while(true) do
Line 3,721 ⟶ 4,767:
if (not change) then break end if:
end do:
arr;</langsyntaxhighlight>
{{Out|Output}}
<pre>[0,0,2,3,3,8,17,36,40,72]</pre>
Line 3,727 ⟶ 4,773:
=={{header|Mathematica}}/{{header|Wolfram Language}}==
===Using pattern matching===
<langsyntaxhighlight Mathematicalang="mathematica">bubbleSort[{w___, x_, y_, z___}] /; x > y := bubbleSort[{w, y, x, z}]
bubbleSort[sortedList_] := sortedList
bubbleSort[{10, 3, 7, 1, 4, 3, 8, 13, 9}]</langsyntaxhighlight>
{{out}}
<pre>{1, 3, 3, 4, 7, 8, 9, 10, 13}</pre>
===Classic version===
<langsyntaxhighlight Mathematicalang="mathematica">ClearAll[BubbleSort]
BubbleSort[in_List] := Module[{x = in, l = Length[in], swapped},
swapped = True;
Line 3,749 ⟶ 4,795:
x
]
BubbleSort[{1, 12, 3, 7, 2, 8, 4, 7, 6}]</langsyntaxhighlight>
{{out}}
<pre>{1, 2, 3, 4, 6, 7, 7, 8, 12}</pre>
Line 3,755 ⟶ 4,801:
=={{header|MATLAB}}==
 
<langsyntaxhighlight MATLABlang="matlab">function list = bubbleSort(list)
 
hasChanged = true;
Line 3,774 ⟶ 4,820:
end %for
end %while
end %bubbleSort</langsyntaxhighlight>
 
{{out}}
Line 3,782 ⟶ 4,828:
 
1 2 3 4 5 6 7 8 9</pre>
 
=={{header|Maxima}}==
<syntaxhighlight lang="maxima">
bubble_sort(u) := block(
[n: length(u), swapped: true, temp],
while swapped do (
swapped: false,
for i: 1 thru n - 1 do (
if u[i] > u[i + 1] then (
temp: u[i],
u[i]: u[i + 1],
u[i + 1]: temp,
swapped: true
)
)
),
u
);
/* Example */
/* sample:[3,65,6,24,24,89,2,59,6]$
bubble_sort(%);
[2,3,6,6,24,24,59,65,89]
*/
</syntaxhighlight>
 
=={{header|MAXScript}}==
<langsyntaxhighlight lang="maxscript">fn bubbleSort arr =
(
while true do
Line 3,800 ⟶ 4,870:
)
arr
)</langsyntaxhighlight>
-- Usage
<langsyntaxhighlight lang="maxscript">myArr = #(9, 8, 7, 6, 5, 4, 3, 2, 1)
myArr = bubbleSort myArr</langsyntaxhighlight>
 
=={{header|MMIX}}==
<langsyntaxhighlight lang="mmix">Ja IS $127
 
LOC Data_Segment
Line 3,885 ⟶ 4,955:
JMP 2B % loop
1H XOR $255,$255,$255
TRAP 0,Halt,0 % exit(0)</langsyntaxhighlight>
 
=={{header|Modula-2}}==
<langsyntaxhighlight lang="modula2">PROCEDURE BubbleSort(VAR a: ARRAY OF INTEGER);
VAR
changed: BOOLEAN;
Line 3,906 ⟶ 4,976:
END
UNTIL NOT changed
END BubbleSort;</langsyntaxhighlight>
 
=={{header|Modula-3}}==
 
<langsyntaxhighlight lang="modula3">MODULE Bubble;
 
PROCEDURE Sort(VAR a: ARRAY OF INTEGER) =
Line 3,929 ⟶ 4,999:
END;
END Sort;
END Bubble.</langsyntaxhighlight>
 
=={{header|N/t/roff}}==
Line 3,941 ⟶ 5,011:
{{works with|GROFF (GNU Troff)|1.22.2}}
 
<langsyntaxhighlight Nlang="n/t/roff">
.ig
Bubble sort algorithm in Troff
Line 4,012 ⟶ 5,082:
.nr Ai 0 1
.while \n(Ai<\n(Ac \n[A\n+[Ai]]
</syntaxhighlight>
</lang>
 
===Output===
Line 4,021 ⟶ 5,091:
=={{header|Nanoquery}}==
{{trans|Python}}
<langsyntaxhighlight Nanoquerylang="nanoquery">def bubble_sort(seq)
changed = true
 
Line 4,048 ⟶ 5,118:
testset = bubble_sort(testset)
println testset
end</langsyntaxhighlight>
 
{{out}}
Line 4,057 ⟶ 5,127:
=={{header|Nemerle}}==
===Functional===
<langsyntaxhighlight Nemerlelang="nemerle">using System;
using System.Console;
 
Line 4,099 ⟶ 5,169:
WriteLine(Bubblesort(several));
}
}</langsyntaxhighlight>
===Imperative===
{{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.
<langsyntaxhighlight Nemerlelang="nemerle">using System;
using System.Console;
 
Line 4,135 ⟶ 5,205:
Write($"$i ");
}
}</langsyntaxhighlight>
 
=={{header|NetRexx}}==
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref savelog symbols binary
 
Line 4,174 ⟶ 5,244:
 
return list
</syntaxhighlight>
</lang>
{{out}}
<pre style="height: 20ex; overflow: scroll;">
Line 4,199 ⟶ 5,269:
===Translation of Pseudocode===
This version is a direct implementation of this task's pseudocode.
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref savelog symbols binary
 
Line 4,245 ⟶ 5,315:
method isFalse public constant binary returns boolean
return \isTrue
</syntaxhighlight>
</lang>
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">proc bubbleSort[T](a: var openarray[T]) =
var t = true
for n in countdown(a.len-2, 0):
Line 4,260 ⟶ 5,330:
var a = @[4, 65, 2, -31, 0, 99, 2, 83, 782]
bubbleSort a
echo a</langsyntaxhighlight>
{{out}}
<pre>@[-31, 0, 2, 2, 4, 65, 83, 99, 782]</pre>
 
=={{header|Oberon-2}}==
<syntaxhighlight lang="oberon2">MODULE Bubble;
 
IMPORT Out;
 
TYPE
TItem = INTEGER;
VAR
I:LONGINT;
A:ARRAY 10 OF TItem;
PROCEDURE Init(VAR A:ARRAY OF TItem);
BEGIN
A[0] := 1; A[1] := 10; A[2] := 2; A[3] := 5;
A[4] := -1; A[5] := 5; A[6] := -19; A[7] := 4;
A[8] := 23; A[9] := 0;
END Init;
 
PROCEDURE Swap(VAR A,B:TItem);
VAR
Temp:TItem;
BEGIN
Temp := A;
A := B;
B := Temp;
END Swap;
 
PROCEDURE BubbleSort(VAR A:ARRAY OF TItem);
VAR
N,Newn,I:LONGINT;
BEGIN
N := LEN(A)-1;
REPEAT
Newn := 0;
FOR I := 1 TO N DO
IF A[I-1] > A[I] THEN
Swap(A[I-1], A[I]);
Newn := I;
END;
END;
N := Newn;
UNTIL N = 0;
END BubbleSort;
 
BEGIN
Init(A);
Out.String("Before sorting: "); Out.Ln;
FOR I := 0 TO LEN(A)-1 DO Out.Int(A[I],0); Out.Char(' '); END;
Out.Ln;
BubbleSort(A);
Out.String("After sorting: "); Out.Ln;
FOR I := 0 TO LEN(A)-1 DO Out.Int(A[I],0); Out.Char(' '); END;
Out.Ln;
END Bubble.
</syntaxhighlight>
 
{{Out}}
<pre>Before sorting:
1 10 2 5 -1 5 -19 4 23 0
After sorting:
-19 -1 0 1 2 4 5 5 10 23
</pre>
 
=={{header|Objeck}}==
{{trans|C}}
<langsyntaxhighlight lang="objeck">
function : Swap(p : Int[]) ~ Nil {
t := p[0];
Line 4,286 ⟶ 5,420:
while (sorted = false);
}
</syntaxhighlight>
</lang>
 
=={{header|Objective-C}}==
<langsyntaxhighlight lang="objc">- (NSArray *) bubbleSort:(NSMutableArray *)unsorted {
BOOL done = false;
Line 4,304 ⟶ 5,438:
return unsorted;
}
</syntaxhighlight>
</lang>
 
=={{header|OCaml}}==
Line 4,310 ⟶ 5,444:
 
This version checks for changes in a separate step for simplicity.
<langsyntaxhighlight lang="ocaml">let rec bsort s =
let rec _bsort = function
| x :: x2 :: xs when x > x2 ->
Line 4,320 ⟶ 5,454:
let t = _bsort s in
if t = s then t
else bsort t</langsyntaxhighlight>
 
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.
<langsyntaxhighlight lang="ocaml">let rec bsort s =
let rec _bsort = function
| x :: x2 :: xs when x > x2 -> begin
Line 4,339 ⟶ 5,473:
match _bsort s with
| None -> s
| Some s2 -> bsort s2</langsyntaxhighlight>
 
=={{header|Octave}}==
<langsyntaxhighlight lang="octave">function s = bubblesort(v)
itemCount = length(v);
do
Line 4,355 ⟶ 5,489:
until(hasChanged == false)
s = v;
endfunction</langsyntaxhighlight>
 
<langsyntaxhighlight lang="octave">v = [9,8,7,3,1,100];
disp(bubblesort(v));</langsyntaxhighlight>
 
=={{header|Ol}}==
<langsyntaxhighlight lang="scheme">
(define (bubble-sort x ??)
(define (sort-step l)
Line 4,380 ⟶ 5,514:
(print
(bubble-sort (iota 100) <))
</syntaxhighlight>
</lang>
 
{{Out}}
Line 4,393 ⟶ 5,527:
{{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.
<langsyntaxhighlight ooRexxlang="oorexx">/* Rexx */
Do
placesList = sampleData()
Line 4,455 ⟶ 5,589:
Exit
 
</syntaxhighlight>
</lang>
{{out}}
<pre style="height: 20ex; overflow: scroll;">
Line 4,479 ⟶ 5,613:
===Translation of Pseudocode===
This version is a direct implementation of this task's pseudocode.
<langsyntaxhighlight ooRexxlang="oorexx">/* Rexx */
Do
placesList = sampleData()
Line 4,551 ⟶ 5,685:
isFalse: procedure
return \isTrue()
</syntaxhighlight>
</lang>
 
===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.
<langsyntaxhighlight ooRexxlang="oorexx">/* Rexx */
Do
placesList. = ''
Line 4,616 ⟶ 5,750:
End
Exit
</syntaxhighlight>
</lang>
 
=={{header|Oz}}==
In-place sorting of mutable arrays:
<langsyntaxhighlight lang="oz">declare
proc {BubbleSort Arr}
proc {Swap I J}
Line 4,642 ⟶ 5,776:
in
{BubbleSort Arr}
{Inspect Arr}</langsyntaxhighlight>
 
Purely-functional sorting of immutable lists:
<langsyntaxhighlight lang="oz">declare
local
fun {Loop Xs Changed ?IsSorted}
Line 4,669 ⟶ 5,803:
end
in
{Show {BubbleSort [3 1 4 1 5 9 2 6 5]}}</langsyntaxhighlight>
 
=={{header|PARI/GP}}==
<langsyntaxhighlight lang="parigp">bubbleSort(v)={
for(i=1,#v-1,
for(j=i+1,#v,
Line 4,683 ⟶ 5,817:
);
v
};</langsyntaxhighlight>
 
=={{header|Pascal}}==
<langsyntaxhighlight lang="pascal">procedure bubble_sort(var list: array of real);
var
i, j, n: integer;
Line 4,700 ⟶ 5,834:
list[j + 1] := t;
end;
end;</langsyntaxhighlight>
 
Usage:<langsyntaxhighlight lang="pascal">var
list: array[0 .. 9] of real;
// ...
bubble_sort(list);</langsyntaxhighlight>
 
=={{header|Pebble}}==
<syntaxhighlight lang="pebble">;bubble sort example for x86 DOS
;compiles to 549 bytes com file
 
program examples\bubble
 
data
 
int sorting[0]
int index[0]
int size[10]
int temp1[0]
int temp2[0]
 
int@ list[10]
 
begin
 
call fill
call sort
call output
 
pause
kill
 
end
 
sub fill
 
0 [index]
 
label loopfill
 
echo "Enter value #" \
echo [index]
echo ": " \
 
input @list{[index]}
 
+1 [index]
 
if [index] < [size] then loopfill
 
ret
 
sub sort
 
label loopsort
 
0 [sorting]
 
0 [index]
 
label process
 
[temp1] = [index] + 1
 
if @list{[index]} > @list{[temp1]} then
 
[temp2] = @list{[index]}
 
@list{[index]} = @list{[temp1]}
@list{[temp1]} = [temp2]
 
[sorting] = 1
 
endif
 
+1 [index]
 
if [index] < [size] - 1 then process
 
if [sorting] = 1 then loopsort
 
ret
 
sub output
 
0 [index]
 
label loopoutput
 
echo [index]
echo " : " \
echo @list{[index]}
crlf
 
+1 [index]
 
if [index] < [size] then loopoutput
 
ret</syntaxhighlight>
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl"># Sorts an array in place
sub bubble_sort {
for my $i (0 .. $#_){
Line 4,715 ⟶ 5,942:
}
}
}</langsyntaxhighlight>
 
Usage:
 
<langsyntaxhighlight lang="perl">my @a = (39, 25, 30, 28, 36, 72, 98, 25, 43, 38);
bubble_sort(@a);</langsyntaxhighlight>
 
=={{header|Phix}}==
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
Line 4,750 ⟶ 5,977:
<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>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 4,759 ⟶ 5,986:
=={{header|PHP}}==
 
<langsyntaxhighlight lang="php">function bubbleSort(array $array){
foreach($array as $i => &$val){
foreach($array as $k => &$val2){
Line 4,771 ⟶ 5,998:
}
return $array;
}</langsyntaxhighlight>
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de bubbleSort (Lst)
(use Chg
(loop
Line 4,782 ⟶ 6,009:
(xchg L (cdr L))
(on Chg) ) )
(NIL Chg Lst) ) ) )</langsyntaxhighlight>
 
=={{header|PL/I}}==
<langsyntaxhighlight lang="pli">/* A primitive bubble sort */
bubble_sort: procedure (A);
declare A(*) fixed binary;
Line 4,800 ⟶ 6,027:
end;
end;
end bubble_sort;</langsyntaxhighlight>
 
=={{header|Pop11}}==
<langsyntaxhighlight lang="pop11">define bubble_sort(v);
lvars n=length(v), done=false, i;
while not(done) do
Line 4,821 ⟶ 6,048:
vars ar = { 10 8 6 4 2 1 3 5 7 9};
bubble_sort(ar);
ar =></langsyntaxhighlight>
 
=={{header|PostScript}}==
<syntaxhighlight lang="postscript">
<lang PostScript>
/bubblesort{
/x exch def
Line 4,846 ⟶ 6,073:
x pstack
}def
</syntaxhighlight>
</lang>
 
=={{header|PowerShell}}==
<langsyntaxhighlight lang="powershell">function bubblesort ($a) {
$l = $a.Length
$hasChanged = $true
Line 4,862 ⟶ 6,089:
}
}
}</langsyntaxhighlight>
 
=={{header|Prolog}}==
Line 4,868 ⟶ 6,095:
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.
<langsyntaxhighlight lang="prolog">%___________________________________________________________________________
% Bubble sort
 
Line 4,887 ⟶ 6,114:
writef(' input=%w\n', [In]),
bubblesort(In, R),
writef('-> %w\n', [R]).</langsyntaxhighlight>
for example:
<pre>?- test.
Line 4,900 ⟶ 6,127:
Should be ISO (but tested only with GNU Prolog).
Note: doesn't constuct list for each swap, only for each pass.
<langsyntaxhighlight lang="prolog">:- initialization(main).
 
 
Line 4,921 ⟶ 6,148:
test([8,9,1,3,4,2,6,5,4]).
 
main :- test(T), bubble_sort(T,_), halt.</langsyntaxhighlight>
{{Out}}
<pre>[8,9,1,3,4,2,6,5,4]
Line 4,928 ⟶ 6,155:
[1,3,2,4,5,4,6,8,9]
[1,2,3,4,4,5,6,8,9]</pre>
 
=={{header|PureBasic}}==
<lang PureBasic>Procedure bubbleSort(Array a(1))
Protected i, itemCount, hasChanged
itemCount = ArraySize(a())
Repeat
hasChanged = #False
itemCount - 1
For i = 0 To itemCount
If a(i) > a(i + 1)
Swap a(i), a(i + 1)
hasChanged = #True
EndIf
Next
Until hasChanged = #False
EndProcedure</lang>
 
=={{header|Python}}==
<langsyntaxhighlight lang="python">def bubble_sort(seq):
"""Inefficiently sort the mutable sequence (list) in place.
seq MUST BE A MUTABLE SEQUENCE.
Line 4,956 ⟶ 6,166:
while changed:
changed = False
for i in xrangerange(len(seq) - 1):
if seq[i] > seq[i+1]:
seq[i], seq[i+1] = seq[i+1], seq[i]
Line 4,967 ⟶ 6,177:
from random import shuffle
 
testset = [_ for _ in range(100)]
testcase = testset[:].copy() # make a copy
shuffle(testcase)
assert testcase != testset # we've shuffled it
bubble_sort(testcase)
assert testcase == testset # we've unshuffled it back into a copy</langsyntaxhighlight>
 
=={{header|Quackery}}==
 
<langsyntaxhighlight Quackerylang="quackery"> [ stack ] is sorted ( --> s )
[ rot tuck over peek
Line 4,998 ⟶ 6,208:
[ 10 random join ]
say "Before: " dup echo cr
say "After: " bubble echo</langsyntaxhighlight>
 
{{out}}
Line 5,007 ⟶ 6,217:
 
=={{header|Qi}}==
<langsyntaxhighlight Qilang="qi">(define bubble-shot
[A] -> [A]
[A B|R] -> [B|(bubble-shot [A|R])] where (> A B)
Line 5,016 ⟶ 6,226:
 
(bubble-sort [6 8 5 9 3 2 2 1 4 7])
</syntaxhighlight>
</lang>
 
=={{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.
<langsyntaxhighlight lang="rsplus">bubbleSort <- function(items)
{
repeat
{
if((itemCount <- length(items)) <= 1) return(items)
hasChanged <- FALSE
itemCount <- itemCount - 1
for(i in 1:seq_len(itemCount))
{
if(items[i] > items[i + 1])
{
items[c(i, i + 1)] <- items[c(i + 1, i)]#The cool trick mentioned above.
hasChanged <- TRUE
}
}
Line 5,040 ⟶ 6,250:
}
#Examples taken from the Haxe solution.
ints <- c(1, 10, 2, 5, -1, 5, -19, 4, 23, 0)
numerics <- c(1, -3.2, 5.2, 10.8, -5.7, 7.3, 3.5, 0, -4.1, -9.5)
strings <- c("We", "hold", "these", "truths", "to", "be", "self-evident", "that", "all", "men", "are", "created", "equal")</langsyntaxhighlight>
 
{{out}}
Line 5,054 ⟶ 6,264:
 
=={{header|Ra}}==
<syntaxhighlight lang="ra">
<lang Ra>
class BubbleSort
**Sort a list with the Bubble Sort algorithm**
Line 5,086 ⟶ 6,296:
list[i + 1] := temp
changed := true
</syntaxhighlight>
</lang>
 
=={{header|Racket}}==
Line 5,092 ⟶ 6,302:
This bubble sort sorts the elelement in the vector v with regard to <?.
 
<langsyntaxhighlight lang="racket">
#lang racket
 
Line 5,109 ⟶ 6,319:
(when again? (loop (- max 1) #f)))
v)
</syntaxhighlight>
</lang>
 
Example: Sorting a vector of length 10 with random entries.
<langsyntaxhighlight lang="racket">
(bubble-sort < (for/vector ([_ 10]) (random 20)))
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
Line 5,120 ⟶ 6,330:
{{works with|Rakudo|#24 "Seoul"}}
 
<syntaxhighlight lang="raku" perl6line>sub bubble_sort (@a) {
for ^@a -> $i {
for $i ^..^ @a -> $j {
Line 5,126 ⟶ 6,336:
}
}
}</langsyntaxhighlight>
 
=={{header|REALbasic}}==
 
Sorts an array of Integers
 
<lang vb>
Dim sortable() As Integer = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
sortable.Shuffle() ' sortable is now randomized
Dim swapped As Boolean
Do
Dim index, bound As Integer
bound = sortable.Ubound
 
While index < bound
If sortable(index) > sortable(index + 1) Then
Dim s As Integer = sortable(index)
sortable.Remove(index)
sortable.Insert(index + 1, s)
swapped = True
End If
index = index + 1
Wend
Loop Until Not swapped
'sortable is now sorted
</lang>
 
=={{header|REXX}}==
===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.
<langsyntaxhighlight 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 show 'before sort' /*show the before array elements. */
Line 5,187 ⟶ 6,371:
return
/*──────────────────────────────────────────────────────────────────────────────────────*/
show: do j=1 for #; say ' element' right(j,length(#)) arg(1)":" @.j; end; return</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the internal array list:}}
<br>(Shown at &nbsp; '''<sup>5</sup>/<sub>6</sub>''' &nbsp; size.)
Line 5,246 ⟶ 6,430:
 
Programming note: &nbsp; a check was made to not exceed REXX's upper range limit of the &nbsp; '''random''' &nbsp; BIF.
<langsyntaxhighlight 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*/
call gen N /*generate the array elements (items). */
Line 5,261 ⟶ 6,445:
/*──────────────────────────────────────────────────────────────────────────────────────*/
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</langsyntaxhighlight>
{{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>
Line 5,270 ⟶ 6,454:
===version 2, random integers, horizontal list===
{{trans|PL/I}}
<langsyntaxhighlight lang="rexx">
/*REXX*/
Call random ,,1000
Line 5,295 ⟶ 6,479:
show:
l=''; Do i=1 To a.0; l=l a.i; End; Say arg(1)':'l
Return</langsyntaxhighlight>
{{out}}
<pre>vorher : 9 17 16 19 5 7 3 20 16 0
Line 5,311 ⟶ 6,495:
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.
<langsyntaxhighlight 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*/
if N=='' | N=="," then N=30 /*Not specified? Then use the default.*/
Line 5,342 ⟶ 6,526:
do s=# for # by -1; say $.s; end /*s*/
say "└"copies('─', #) /*display the horizontal axis at bottom*/
return</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default input:}}
<pre>
Line 5,476 ⟶ 6,660:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">bubbleList = [4,2,1,3]
flag = 0
bubbleSort(bubbleList)
Line 5,494 ⟶ 6,678:
next
end
</syntaxhighlight>
</lang>
 
=={{header|RPL}}==
The bubble algorithm is slow by construction, but since its RPL implementation uses basic stack handling, it is actually quicker than algorithms that work directly on the array.
{{works with|Halcyon Calc|4.2.7}}
≪ '''IF''' DUP SIZE 2 ≥ '''THEN'''
LIST→ → len
≪ len 1 '''FOR''' n
1 n 1 - '''START'''
'''IF''' DUP2 > '''THEN''' SWAP '''END'''
n ROLLD
'''NEXT'''
n ROLLD
-1 '''STEP'''
len →LIST
'''END''' ≫
 
=={{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.
 
<langsyntaxhighlight lang="ruby">class Array
def bubblesort1!
length.times do |j|
Line 5,522 ⟶ 6,722:
ary.bubblesort1!
p ary
# => [3, 4, 6, 6, 8, 23, 78]</langsyntaxhighlight>
 
=={{header|Run BASIC}}==
<lang runbasic>siz = 100
dim data$(siz)
unSorted = 1
 
WHILE unSorted
unSorted = 0
FOR i = 1 TO siz -1
IF data$(i) > data$(i + 1) THEN
tmp = data$(i)
data$(i) = data$(i + 1)
data$(i + 1) = tmp
unSorted = 1
END IF
NEXT
WEND</lang>
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">fn bubble_sort<T: Ord>(values: &mut[T]) {
let mut n = values.len();
let mut swapped = true;
Line 5,574 ⟶ 6,757:
bubble_sort(&mut strings);
println!("After: {:?}", strings);
}</langsyntaxhighlight>
 
=={{header|Sather}}==
<langsyntaxhighlight lang="sather">class SORT{T < $IS_LT{T}} is
private swap(inout a, inout b:T) is
temp ::= a;
Line 5,597 ⟶ 6,780:
end;
end;
end;</langsyntaxhighlight>
 
<langsyntaxhighlight lang="sather">class MAIN is
main is
a:ARRAY{INT} := |10, 9, 8, 7, 6, -10, 5, 4|;
Line 5,605 ⟶ 6,788:
#OUT + a + "\n";
end;
end;</langsyntaxhighlight>
 
This should be able to sort (in ascending order) any object for which <code>is_lt</code> (less than) is defined.
Line 5,613 ⟶ 6,796:
This slightly more complex version of Bubble Sort avoids errors with indices.
 
<langsyntaxhighlight lang="scala">def bubbleSort[T](arr: Array[T])(implicit o: Ordering[T]) {
import o._
val consecutiveIndices = (arr.indices, arr.indices drop 1).zipped
Line 5,628 ⟶ 6,811:
}
} while(hasChanged)
}</langsyntaxhighlight>
 
<langsyntaxhighlight lang="scala">import scala.annotation.tailrec
 
def bubbleSort(xt: List[Int]) = {
Line 5,643 ⟶ 6,826:
}
bubble(xt, Nil, Nil)
}</langsyntaxhighlight>
 
=={{header|Scheme}}==
<langsyntaxhighlight lang="scheme">(define (bubble-sort x gt?)
(letrec
((fix (lambda (f i)
Line 5,660 ⟶ 6,843:
(cons (car l) (sort-step (cdr l))))))))
 
(fix sort-step x)))</langsyntaxhighlight>
 
This solution recursively finds the fixed point of sort-step. A comparison function must be passed to bubblesort. Example usages:
<langsyntaxhighlight lang="scheme">(bubble-sort (list 1 3 5 9 8 6 4 2) >)
(bubble-sort (string->list "Monkey") char<?)</langsyntaxhighlight>
 
Here is the same function, using a different syntax:
 
<langsyntaxhighlight lang="scheme">(define (bsort l gt?)
(define (dosort l)
(cond ((null? (cdr l))
Line 5,680 ⟶ 6,863:
l
(bsort try gt?))))
</syntaxhighlight>
</lang>
For example, you could do
<langsyntaxhighlight lang="scheme">(bsort > '(2 4 6 2))
(1 2 3)</langsyntaxhighlight>
 
=={{header|Scilab}}==
<syntaxhighlight lang="text">function b=BubbleSort(a)
n=length(a)
swapped=%T
Line 5,701 ⟶ 6,884:
end
b=a
endfunction BubbleSort</langsyntaxhighlight>
{{out}}
<pre style="height:20ex">-->y=[5 4 3 2 1]
Line 5,714 ⟶ 6,897:
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">const proc: bubbleSort (inout array elemType: arr) is func
local
var boolean: swapped is FALSE;
Line 5,731 ⟶ 6,914:
end for;
until not swapped;
end func;</langsyntaxhighlight>
 
Original source: [http://seed7.sourceforge.net/algorith/sorting.htm#bubbleSort]
Line 5,737 ⟶ 6,920:
=={{header|Shen}}==
Bubble sort a vector in-place, using the < operator for comparison.
<langsyntaxhighlight lang="shen">(tc +)
 
(define swap
Line 5,763 ⟶ 6,946:
{ (vector number) --> (vector number) }
A -> (let N (limit A)
(bubble-h (one-pass A N false 2) A N)))</langsyntaxhighlight>
 
<langsyntaxhighlight lang="shen">(datatype some-globals
 
__________
Line 5,776 ⟶ 6,959:
(vector-> (value *arr*) 4 2)
(vector-> (value *arr*) 5 8)
(bubble-sort (value *arr*))</langsyntaxhighlight>
 
Here is a more idiomatic implementation:
{{trans|Qi}}
 
<langsyntaxhighlight lang="shen">(tc +)
 
(define bubble-shot
Line 5,791 ⟶ 6,974:
(define bubble-sort
{ (vector number) --> (vector number) }
X -> (fix (function bubble-shot) X))</langsyntaxhighlight>
 
<langsyntaxhighlight lang="shen">(bubble-sort (@v 5 1 4 2 3 <>))</langsyntaxhighlight>
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">func bubble_sort(arr) {
loop {
var swapped = false
Line 5,808 ⟶ 6,991:
}
return arr
}</langsyntaxhighlight>
 
=={{header|Simula}}==
<langsyntaxhighlight lang="simula">BEGIN
 
PROCEDURE BUBBLESORT(A); NAME A; INTEGER ARRAY A;
Line 5,855 ⟶ 7,038:
OUTIMAGE;
 
END;</langsyntaxhighlight>
{{out}}
<pre>
Line 5,864 ⟶ 7,047:
A straight translation from the pseudocode above. Swap is done with a [[wp:Smalltalk#Code_blocks|block closure]].
 
<langsyntaxhighlight lang="smalltalk">|item swap itemCount hasChanged|
item := #(1 4 5 6 10 8 7 61 0 -3) copy.
swap :=
Line 5,881 ⟶ 7,064:
[swap value: index value: index + 1.
hasChanged := true]].
hasChanged] whileTrue.</langsyntaxhighlight>
 
=={{header|SNOBOL4}}==
 
<langsyntaxhighlight SNOBOL4lang="snobol4">* # Sort array in place, return array
define('bubble(a,alen)i,j,ub,tmp') :(bubble_end)
bubble i = 1; ub = alen
Line 5,908 ⟶ 7,091:
sloop j = j + 1; str = str arr<j> ' ' :s(sloop)
output = trim(str)
end</langsyntaxhighlight>
 
{{out}}
Line 5,920 ⟶ 7,103:
 
Static analysis of this code shows that it is guaranteed free of any run-time error when called from any other SPARK code.
<langsyntaxhighlight Adalang="ada">package Bubble
is
 
Line 5,956 ⟶ 7,139:
 
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.
<langsyntaxhighlight Adalang="ada">package Bubble
is
Line 6,007 ⟶ 7,190:
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.
<pre>
Line 6,022 ⟶ 7,205:
 
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.
<langsyntaxhighlight Adalang="ada">package body Bubble
is
procedure Sort (A : in out Arr)
Line 6,085 ⟶ 7,268:
 
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.
<pre>bubble_sort_rule(1): sorted(A, I, J)
Line 6,159 ⟶ 7,342:
 
File '''bubble.ads''':
<langsyntaxhighlight lang="ada">package Bubble with SPARK_Mode is
 
type Arr is array (Integer range <>) of Integer;
Line 6,181 ⟶ 7,364:
end Bubble;
</syntaxhighlight>
</lang>
 
File '''bubble.adb''':
<langsyntaxhighlight lang="ada">package body Bubble with SPARK_Mode is
procedure Sort (A : in out Arr)
Line 6,218 ⟶ 7,401:
end Bubble;
</syntaxhighlight>
</lang>
 
File '''main.adb''':
<langsyntaxhighlight lang="ada">with Ada.Integer_Text_IO;
with Bubble;
 
Line 6,232 ⟶ 7,415:
end loop;
end Main;
</syntaxhighlight>
</lang>
 
File '''bubble.gpr''':
<langsyntaxhighlight lang="ada">project Bubble is
 
for Main use ("main.adb");
 
end Bubble;
</syntaxhighlight>
</lang>
 
To verify the program, execute the command: '''gnatprove -P bubble.gpr -j0 --level=2'''
Line 6,275 ⟶ 7,458:
=={{header|Standard ML}}==
Assumes a list of integers.
<syntaxhighlight lang="sml">
<pre>
fun bubble_select [] = []
| bubble_select [a] = [a]
Line 6,283 ⟶ 7,466:
fun bubblesort [] = []
| bubblesort (x::xs) =bubble_select (x::(bubblesort xs))
</syntaxhighlight>
</pre>
 
=={{header|Stata}}==
<langsyntaxhighlight lang="stata">mata
function bubble_sort(a) {
n = length(a)
Line 6,302 ⟶ 7,485:
}
}
end</langsyntaxhighlight>
 
=={{header|Swift}}==
<langsyntaxhighlight Swiftlang="swift">func bubbleSort<T:Comparable>(list:inout[T]) {
var done = false
while !done {
Line 6,321 ⟶ 7,504:
print(list1)
bubbleSort(list: &list1)
print(list1)</langsyntaxhighlight>
 
=={{header|Symsyn}}==
<syntaxhighlight lang="symsyn">
<lang Symsyn>
 
x : 23 : 15 : 99 : 146 : 3 : 66 : 71 : 5 : 23 : 73 : 19
Line 6,369 ⟶ 7,552:
" $r $s " []
return
</syntaxhighlight>
</lang>
 
=={{header|Tailspin}}==
<langsyntaxhighlight lang="tailspin">
templates bubblesort
templates bubble
Line 6,394 ⟶ 7,577:
[4,5,3,8,1,2,6,7,9,8,5] -> bubblesort -> !OUT::write
</syntaxhighlight>
</lang>
 
=={{header|Tcl}}==
{{tcllib|struct::list}}
<langsyntaxhighlight lang="tcl">package require Tcl 8.5
package require struct::list
 
Line 6,418 ⟶ 7,601:
}
 
puts [bubblesort {8 6 4 2 1 3 5 7 9}] ;# => 1 2 3 4 5 6 7 8 9</langsyntaxhighlight>
 
Idiomatic code uses the builtin <code>lsort</code> instead, which is a stable O(''n'' log ''n'') sort.
 
=={{header|TI-83 BASIC}}==
Input your data into L<sub>1</sub> and run this program to organize it.
:L<sub>1</sub>→L<sub>2</sub>
:1+dim(L<sub>2</sub>)→N
:For(D,1,dim(L<sub>2</sub>))
:N-1→N
:0→I
:For(C,1,dim(L<sub>2</sub>)-2)
:For(A,dim(L<sub>2</sub>)-N+1,dim(L<sub>2</sub>)-1)
:If L<sub>2</sub>(A)&gt;L<sub>2</sub>(A+1)
:Then
:1→I
:L<sub>2</sub>(A)→B
:L<sub>2</sub>(A+1)→L<sub>2</sub>(A)
:B→L<sub>2</sub>(A+1)
:End
:End
:End
:If I=0
:Goto C
:End
:Lbl C
:If L<sub>2</sub>(1)&gt;L<sub>2</sub>(2)
:Then
:L<sub>2</sub>(1)→B
:L<sub>2</sub>(2)→L<sub>2</sub>(1)
:B→L<sub>2</sub>(2)
:End
:DelVar A
:DelVar B
:DelVar C
:DelVar D
:DelVar N
:DelVar I
:Return
 
[[wp:Odd-even sort|Odd-Even Bubble Sort]] (same IO):
:"ODD-EVEN"
:L<sub>1</sub>→L<sub>2</sub>(
:1+dim(L<sub>2</sub>)→N
:For(D,1,dim(L<sub>2</sub>))
:N-1→N
:0→O
:For(C,1,dim(L<sub>2</sub>)-2)
:For(A,dim(L<sub>2</sub>)-N+2,dim(L<sub>2</sub>)-1,2)
:If L<sub>2</sub>(A)>L<sub>2</sub>(A+1)
:Then
:1→O
:L<sub>2</sub>(A)→B
:L<sub>2</sub>(A+1)→L<sub>2</sub>(A)
:B→L<sub>2</sub>(A+1)
:End
:End
:For(A,dim(L<sub>2</sub>)-N+1,dim(L<sub>2</sub>)-1,2)
:If L<sub>2</sub>(A)>L<sub>2</sub>(A+1)
:Then
:1→O
:L<sub>2</sub>(A)→B
:L<sub>2</sub>(A+1)→L<sub>2</sub>(A)
:B→L<sub>2</sub>(A+1)
:End
:End
:End
:If O=0
:Goto C
:End
:Lbl C
:If L<sub>2</sub>(1)>L<sub>2</sub>(2)
:Then
:L<sub>2</sub>(1)→B
:L<sub>2</sub>(2)→L<sub>2</sub>(1)
:B→L<sub>2</sub>(2)
:End
:DelVar A
:DelVar B
:DelVar C
:DelVar D
:DelVar N
:DelVar O
:Return
 
Implementation of the pseudo code given at the top of the page. Place data to be sorted in L<sub>1</sub>
:dim(L<sub>1</sub>)→D
:Repeat C=0
:0→C
:D–1→D
:For(I,1,D)
:If L<sub>1</sub>(I)>L<sub>1</sub>(I+1):Then
:L<sub>1</sub>(I)→C
:L<sub>1</sub>(I+1)→L<sub>1</sub>(I)
:C→L<sub>1</sub>(I+1)
:1→C
:End
:End
:End
:L<sub>1</sub>
 
=={{header|Toka}}==
Toka does not have a bubble sort predefined, but it is easy to code a simple one:
 
<langsyntaxhighlight lang="toka">#! A simple Bubble Sort function
value| array count changed |
[ ( address count -- )
Line 6,559 ⟶ 7,645:
foo 10 .array
foo 10 bsort
foo 10 .array</langsyntaxhighlight>
 
=={{header|TorqueScript}}==
 
<langsyntaxhighlight TorqueScriptlang="torquescript">//Note that we're assuming that the list of numbers is separated by tabs.
function bubbleSort(%list)
{
Line 6,580 ⟶ 7,666:
}
return %list;
}</langsyntaxhighlight>
 
=={{header|uBasic/4tH}}==
<lang>PRINT "Bubble sort:"
n = FUNC (_InitArray)
PROC _ShowArray (n)
PROC _Bubblesort (n)
PROC _ShowArray (n)
PRINT
END
_Bubblesort PARAM(1) ' Bubble sort
LOCAL (2)
 
DO
b@ = 0
FOR c@ = 1 TO a@-1
IF @(c@-1) > @(c@) THEN PROC _Swap (c@, c@-1) : b@ = c@
NEXT
a@ = b@
UNTIL b@ = 0
LOOP
 
RETURN
_Swap PARAM(2) ' Swap two array elements
PUSH @(a@)
@(a@) = @(b@)
@(b@) = POP()
RETURN
_InitArray ' Init example array
PUSH 4, 65, 2, -31, 0, 99, 2, 83, 782, 1
FOR i = 0 TO 9
@(i) = POP()
NEXT
RETURN (i)
_ShowArray PARAM (1) ' Show array subroutine
FOR i = 0 TO a@-1
PRINT @(i),
NEXT
PRINT
RETURN</lang>
 
=={{header|Unicon}}==
Line 6,636 ⟶ 7,672:
 
=={{header|UnixPipes}}==
<langsyntaxhighlight lang="bash">rm -f _sortpass
 
reset() {
Line 6,658 ⟶ 7,694:
}
 
cat to.sort | bubblesort</langsyntaxhighlight>
 
=={{header|Ursala}}==
The bubblesort function is parameterized by a relational predicate.
<langsyntaxhighlight Ursalalang="ursala">#import nat
 
bubblesort "p" = @iNX ^=T ^llPrEZryPrzPlrPCXlQ/~& @l ~&aitB^?\~&a "p"?ahthPX/~&ahPfatPRC ~&ath2fahttPCPRC
Line 6,668 ⟶ 7,704:
#cast %nL
 
example = bubblesort(nleq) <362,212,449,270,677,247,567,532,140,315></langsyntaxhighlight>
{{out}}
<pre><140,212,247,270,315,362,449,532,567,677></pre>
 
=={{header|Vala}}==
<langsyntaxhighlight lang="vala">void swap(int[] array, int i1, int i2) {
if (array[i1] == array[i2])
return;
Line 6,701 ⟶ 7,737:
foreach (int i in array)
print("%d ", i);
}</langsyntaxhighlight>
{{out}}
<pre>
Line 6,707 ⟶ 7,743:
</pre>
 
=={{header|VBAV (Vlang)}}==
<syntaxhighlight lang="v (vlang)">fn bubble(mut arr []int) {
{{trans|Phix}}<lang vb>Private Function bubble_sort(s As Variant) As Variant
Dim tmp As Variant
Dim changed As Boolean
For j = UBound(s) To 1 Step -1
changed = False
For i = 1 To j - 1
If s(i) > s(i + 1) Then
tmp = s(i)
s(i) = s(i + 1)
s(i + 1) = tmp
changed = True
End If
Next i
If Not changed Then
Exit For
End If
Next j
bubble_sort = s
End Function
Public Sub main()
s = [{4, 15, "delta", 2, -31, 0, "alfa", 19, "gamma", 2, 13, "beta", 782, 1}]
Debug.Print "Before: "
Debug.Print Join(s, ", ")
Debug.Print "After: "
Debug.Print Join(bubble_sort(s), ", ")
End Sub</lang>{{out}}
<pre>Before:
4, 15, delta, 2, -31, 0, alfa, 19, gamma, 2, 13, beta, 782, 1
After:
-31, 0, 1, 2, 2, 4, 13, 15, 19, 782, alfa, beta, delta, gamma</pre>
 
=={{header|VBScript}}==
Doing the decr and incr thing is superfluous, really. I just had stumbled over the byref thing for <code>swap</code> and wanted to see where else it would work.
 
For those unfamiliar with Perth, WA Australia, the five strings being sorted are names of highways.
 
=====Implementation=====
<lang vb>
sub decr( byref n )
n = n - 1
end sub
 
sub incr( byref n )
n = n + 1
end sub
 
sub swap( byref a, byref b)
dim tmp
tmp = a
a = b
b = tmp
end sub
 
function bubbleSort( a )
dim changed
dim itemCount
itemCount = ubound(a)
do
changed = false
decr itemCount
for i = 0 to itemCount
if a(i) > a(i+1) then
swap a(i), a(i+1)
changed = true
end if
next
loop until not changed
bubbleSort = a
end function
</lang>
 
=====Invocation=====
<lang vb>
dim a
a = array( "great eastern", "roe", "stirling", "albany", "leach")
wscript.echo join(a,", ")
bubbleSort a
wscript.echo join(a,", ")
</lang>
 
{{out}}
<pre>
great eastern, roe, stirling, albany, leach
albany, great eastern, leach, roe, stirling
</pre>
 
=={{header|Visual Basic .NET}}==
'''Platform:''' [[.NET]]
 
{{works with|Visual Basic .NET|9.0+}}
<lang vbnet>Do Until NoMoreSwaps = True
NoMoreSwaps = True
For Counter = 1 To (NumberOfItems - 1)
If List(Counter) > List(Counter + 1) Then
NoMoreSwaps = False
Temp = List(Counter)
List(Counter) = List(Counter + 1)
List(Counter + 1) = Temp
End If
Next
NumberOfItems = NumberOfItems - 1
Loop</lang>
 
=={{header|Vlang}}==
<lang vlang>fn bubble(mut arr []int) {
println('Input: ${arr.str()}')
mut count := arr.len
Line 6,840 ⟶ 7,771:
mut arr := [3, 5, 2, 1, 4]
bubble(mut arr)
}</langsyntaxhighlight>
{{out}}
<pre>Input: [3, 5, 2, 1, 4]
Line 6,847 ⟶ 7,778:
=={{header|Wren}}==
Based on the pseudo-code in the Wikipedia article.
<langsyntaxhighlight ecmascriptlang="wren">var bubbleSort = Fn.new { |a|
var n = a.count
if (n < 2) return
Line 6,864 ⟶ 7,795:
}
 
var asarray = [ [4, 65, 2, -31, 0, 99, 2, 83, 782, 1], [7, 5, 2, 6, 1, 4, 2, 6, 3] ]
for (a in asarray) {
System.print("Before: %(a)")
bubbleSort.call(a)
System.print("After : %(a)")
System.print()
}</langsyntaxhighlight>
 
{{out}}
Line 6,883 ⟶ 7,814:
=={{header|X86 Assembly}}==
Translation of XPL0. Assemble with tasm, tlink /t
<langsyntaxhighlight lang="asm"> .model tiny
.code
.486
Line 6,912 ⟶ 7,843:
popa
ret
end start</langsyntaxhighlight>
 
{{out}}
Line 6,920 ⟶ 7,851:
 
=={{header|Xojo}}==
<langsyntaxhighlight lang="xojo">Dim temp, count As Integer
Dim isDirty As Boolean
count = Ubound(list) // count the array size
Line 6,935 ⟶ 7,866:
End
Next
Loop Until isDirty = False // if we made it without touching the data then we are done</langsyntaxhighlight>
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">include c:\cxpl\codes; \intrinsic 'code' declarations
string 0; \use zero-terminated strings
 
Line 6,961 ⟶ 7,892:
BSort(Str, StrLen(Str));
Text(0, Str); CrLf(0);
]</langsyntaxhighlight>
 
{{out}}
Line 6,967 ⟶ 7,898:
" .Pabcdeefghiiijklmnoooqrstuuvwxyz"
</pre>
 
=={{header|Yabasic}}==
<lang Yabasic>// Animated sort.
// Original idea by William Tang, obtained from MicroHobby 25 Years (https://microhobby.speccy.cz/zxsf/MH-25Years.pdf)
 
clear screen
 
n=15 : m=18 : y=9 : t$=chr$(17)+chr$(205)+chr$(205)
dim p(n), p$(n)
 
for x=1 TO n
p(x)=ran(15)+1
p$(x)=str$(p(x),"##.######")
print at(0,x) p$(x)
next x
 
for j=1 to n-1
for i=j+1 to n
l=n+j-i+1
if p(j) > p(l) then
print color("yellow","red") at(0,j) p$(j)
if l<>m then
for x=m to l step sig(l-m): print at(18,x) t$ : print at (18,x+sig(m-l)) " " : pause .02 : next x
end if
for x=17 TO y step -1 : print at(x,l) t$+" " : pause .02 : next x
for x=0 TO 10 : print at(x,l) " "+p$(l)+t$ : pause .02 : next x
for x=l TO j STEP -1 : print at(11,x) p$(l)+t$ : print at(11,x+1) " " : pause .02 : next x
print at(0,j) " "
for x=j+1 TO l-1 : print color("yellow","red") at(0,x) p$(j) : pause .02 : print at(0,x) p$(x) : pause .02 : next x
print at(0,l) p$(j)
for x=10 TO 0 step -1 : print at(x,j) p$(l)+t$+" " : pause .02 : next x
for x=y TO 17 : print at(x,j) " "+t$ : pause .02 : next x
m=j
t=p(l) : tem$=p$(l)
p(l)=p(j) : p$(l)=p$(j)
p(j)=t : p$(j)=tem$
end if
pause .02
next i
next j
 
for x=m TO 18 : print at(18,x-1) " " : print at(18,x) t$ : pause .02 : next x
</lang>
 
=={{header|Yorick}}==
<langsyntaxhighlight lang="yorick">func bubblesort(&items) {
itemCount = numberof(items);
do {
Line 7,024 ⟶ 7,912:
}
} while(hasChanged);
}</langsyntaxhighlight>
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">fcn bubbleSort(list){
itemCount := list.len();
do{
Line 7,039 ⟶ 7,927:
}while(hasChanged);
list
}</langsyntaxhighlight>
Or, punting early termination:
<langsyntaxhighlight lang="zkl">fcn bubbleSort(list){
foreach n,index in ([list.len()-1..0,-1],n){
if (list[index] > list[index + 1]) list.swap(index,index + 1);
}
list
}</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">bubbleSort("This is a test".split("")).println();</langsyntaxhighlight>
{{out}}
<pre>L(" "," "," ","T","a","e","h","i","i","s","s","s","t","t")</pre>
 
=={{header|ZX Spectrum Basic}}==
<lang zxbasic>5000 CLS
5002 LET a$="": FOR f=1 TO 64: LET a$=a$+CHR$ (32+INT (RND*96)): NEXT f
5004 PRINT a$; AT 10,0;"ZigZag BubbleSORT"
5010 LET la=LEN a$
5011 LET i=1: LET u=0
5020 LET d=0: LET p=(u=0)-(u=1)
5021 LET l=(i AND u=0)+(la-i+u AND u=1)
5030 IF u=0 THEN IF a$(l+1)>=a$(l) THEN GO TO 5050
5031 IF u=1 THEN IF a$(l-1)<=a$(l) THEN GO TO 5050
5040 LET d=1
5042 LET t$=a$(l+p)
5043 LET a$(l+p)=a$(l)
5044 LET a$(l)=t$
5050 LET l=l+p
5051 PRINT AT 10,21;a$(l);AT 12,0;a$
5055 IF l<=la-i AND l>=i THEN GO TO 5023
5061 LET i=i+NOT u
5063 LET u=NOT u
5064 IF d AND i<la THEN GO TO 5020
5072 PRINT AT 12,0;a$
9000 STOP </lang>
 
The traditional solution:
 
<lang zxbasic> 10 LET siz=32
20 DIM d$(siz)
30 REM Populate d$
40 FOR n=1 TO siz: LET d$(n)=CHR$ (48+INT (RND*75)): NEXT n
50 PRINT d$
60 LET unSorted=0
70 FOR i=1 TO siz-1
80 IF d$(i)>d$(i+1) THEN LET t$=d$(i): LET d$(i)=d$(i+1): LET d$(i+1)=t$: LET unSorted=1
90 NEXT i
100 IF unSorted THEN LET siz=siz-1: GO TO 60
110 PRINT d$</lang>
 
{{omit from|GUISS}}
{{omit from|Tiny BASIC}}
23

edits