Sorting algorithms/Bubble sort: Difference between revisions
Content added Content deleted
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
|||
Line 40: | Line 40: | ||
{{trans|Python}} |
{{trans|Python}} |
||
< |
<syntaxhighlight lang="11l">F bubble_sort(&seq) |
||
V changed = 1B |
V changed = 1B |
||
L changed == 1B |
L changed == 1B |
||
Line 54: | Line 54: | ||
assert(testcase != testset) |
assert(testcase != testset) |
||
bubble_sort(&testcase) |
bubble_sort(&testcase) |
||
assert(testcase == testset)</ |
assert(testcase == testset)</syntaxhighlight> |
||
=={{header|360 Assembly}}== |
=={{header|360 Assembly}}== |
||
For maximum compatibility, this program uses only the basic instruction set. |
For maximum compatibility, this program uses only the basic instruction set. |
||
The program uses also HLASM structured macros (DO,ENDDO,IF,ELSE,ENDIF) for readability and two ASSIST/360 macros (XDECO,XPRNT) to keep the code as short as possible. |
The program uses also HLASM structured macros (DO,ENDDO,IF,ELSE,ENDIF) for readability and two ASSIST/360 macros (XDECO,XPRNT) to keep the code as short as possible. |
||
< |
<syntaxhighlight lang="360 assembly">* Bubble Sort 01/11/2014 & 23/06/2016 |
||
BUBBLE CSECT |
BUBBLE CSECT |
||
USING BUBBLE,R13,R12 establish base registers |
USING BUBBLE,R13,R12 establish base registers |
||
Line 117: | Line 117: | ||
RN EQU 7 n-1 |
RN EQU 7 n-1 |
||
RM EQU 8 more |
RM EQU 8 more |
||
END BUBBLE</ |
END BUBBLE</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 124: | Line 124: | ||
=={{header|6502 Assembly}}== |
=={{header|6502 Assembly}}== |
||
Code can be copied and pasted into Easy6502. Make sure you set the monitor to $1200 and check the check box to view it in action. Bubble Sort's infamous reputation is very well-deserved as this is going to take a few minutes to finish. This example takes a reverse identity table (where the 0th entry is $FF, the first is $FE, and so on) and sorts them in ascending order. Slowly. And the program might not run unless its tab is active in your browser. I'd play Game Boy to pass the time. ;) |
Code can be copied and pasted into Easy6502. Make sure you set the monitor to $1200 and check the check box to view it in action. Bubble Sort's infamous reputation is very well-deserved as this is going to take a few minutes to finish. This example takes a reverse identity table (where the 0th entry is $FF, the first is $FE, and so on) and sorts them in ascending order. Slowly. And the program might not run unless its tab is active in your browser. I'd play Game Boy to pass the time. ;) |
||
< |
<syntaxhighlight lang="6502asm">define z_HL $00 |
||
define z_L $00 |
define z_L $00 |
||
define z_H $01 |
define z_H $01 |
||
Line 178: | Line 178: | ||
jmp BUBBLESORT |
jmp BUBBLESORT |
||
DoneSorting: |
DoneSorting: |
||
rts</ |
rts</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 201: | Line 201: | ||
=={{header|AArch64 Assembly}}== |
=={{header|AArch64 Assembly}}== |
||
{{works with|as|Raspberry Pi 3B version Buster 64 bits}} |
{{works with|as|Raspberry Pi 3B version Buster 64 bits}} |
||
<syntaxhighlight lang="aarch64 assembly"> |
|||
<lang AArch64 Assembly> |
|||
/* ARM assembly AARCH64 Raspberry PI 3B */ |
/* ARM assembly AARCH64 Raspberry PI 3B */ |
||
/* program bubbleSort64.s */ |
/* program bubbleSort64.s */ |
||
Line 371: | Line 371: | ||
.include "../includeARM64.inc" |
.include "../includeARM64.inc" |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|ACL2}}== |
=={{header|ACL2}}== |
||
< |
<syntaxhighlight lang="lisp">(defun bubble (xs) |
||
(if (endp (rest xs)) |
(if (endp (rest xs)) |
||
(mv nil xs) |
(mv nil xs) |
||
Line 398: | Line 398: | ||
(defun bsort (xs) |
(defun bsort (xs) |
||
(bsort-r xs (len xs)))</ |
(bsort-r xs (len xs)))</syntaxhighlight> |
||
=={{header|Action!}}== |
=={{header|Action!}}== |
||
< |
<syntaxhighlight lang="action!">PROC PrintArray(INT ARRAY a INT size) |
||
INT i |
INT i |
||
Line 456: | Line 456: | ||
Test(c,8) |
Test(c,8) |
||
Test(d,12) |
Test(d,12) |
||
RETURN</ |
RETURN</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Bubble_sort.png Screenshot from Atari 8-bit computer] |
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Bubble_sort.png Screenshot from Atari 8-bit computer] |
||
Line 482: | Line 482: | ||
=={{header|ActionScript}}== |
=={{header|ActionScript}}== |
||
< |
<syntaxhighlight lang="actionscript">public function bubbleSort(toSort:Array):Array |
||
{ |
{ |
||
var changed:Boolean = false; |
var changed:Boolean = false; |
||
Line 504: | Line 504: | ||
return toSort; |
return toSort; |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Ada}}== |
=={{header|Ada}}== |
||
{{works with|GCC|4.1.2}} |
{{works with|GCC|4.1.2}} |
||
< |
<syntaxhighlight lang="ada">generic |
||
type Element is private; |
type Element is private; |
||
with function "=" (E1, E2 : Element) return Boolean is <>; |
with function "=" (E1, E2 : Element) return Boolean is <>; |
||
Line 552: | Line 552: | ||
end loop; |
end loop; |
||
New_Line; |
New_Line; |
||
end Main;</ |
end Main;</syntaxhighlight> |
||
=={{header|ALGOL 60}}== |
=={{header|ALGOL 60}}== |
||
{{works with|A60}} |
{{works with|A60}} |
||
< |
<syntaxhighlight lang="algol60">begin |
||
comment Sorting algorithms/Bubble sort - Algol 60; |
comment Sorting algorithms/Bubble sort - Algol 60; |
||
integer nA; |
integer nA; |
||
Line 603: | Line 603: | ||
writetable(1,nA) |
writetable(1,nA) |
||
end |
end |
||
end </ |
end </syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 611: | Line 611: | ||
=={{header|ALGOL 68}}== |
=={{header|ALGOL 68}}== |
||
< |
<syntaxhighlight lang="algol68">MODE DATA = INT; |
||
PROC swap = (REF[]DATA slice)VOID: |
PROC swap = (REF[]DATA slice)VOID: |
||
( |
( |
||
Line 642: | Line 642: | ||
sort(random); |
sort(random); |
||
printf(($"After: "10(g(3))l$,random)) |
printf(($"After: "10(g(3))l$,random)) |
||
)</ |
)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 650: | Line 650: | ||
=={{header|ALGOL W}}== |
=={{header|ALGOL W}}== |
||
< |
<syntaxhighlight lang="algolw">begin |
||
% As algol W does not allow overloading, we have to have type-specific % |
% As algol W does not allow overloading, we have to have type-specific % |
||
% sorting procedures - this bubble sorts an integer array % |
% sorting procedures - this bubble sorts an integer array % |
||
Line 709: | Line 709: | ||
writeData; |
writeData; |
||
end test |
end test |
||
end.</ |
end.</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 720: | Line 720: | ||
In AppleScript, the time taken to set and check a "has changed" boolean repeatedly over the greater part of the sort generally matches or exceeds any time it may save. A more effective optimisation, since the greater value in any pair also takes part in the following comparison, is to keep the greater value in a variable and only fetch one value from the list for the next comparison. |
In AppleScript, the time taken to set and check a "has changed" boolean repeatedly over the greater part of the sort generally matches or exceeds any time it may save. A more effective optimisation, since the greater value in any pair also takes part in the following comparison, is to keep the greater value in a variable and only fetch one value from the list for the next comparison. |
||
< |
<syntaxhighlight lang="applescript">-- In-place bubble sort. |
||
on bubbleSort(theList, l, r) -- Sort items l thru r of theList. |
on bubbleSort(theList, l, r) -- Sort items l thru r of theList. |
||
set listLen to (count theList) |
set listLen to (count theList) |
||
Line 757: | Line 757: | ||
set aList to {61, 23, 11, 55, 1, 94, 71, 98, 70, 33, 29, 77, 58, 95, 2, 52, 68, 29, 27, 37, 74, 38, 45, 73, 10} |
set aList to {61, 23, 11, 55, 1, 94, 71, 98, 70, 33, 29, 77, 58, 95, 2, 52, 68, 29, 27, 37, 74, 38, 45, 73, 10} |
||
sort(aList, 1, -1) -- Sort items 1 thru -1 of aList. |
sort(aList, 1, -1) -- Sort items 1 thru -1 of aList. |
||
return aList</ |
return aList</syntaxhighlight> |
||
{{output}} |
{{output}} |
||
< |
<syntaxhighlight lang="applescript">{1, 2, 10, 11, 23, 27, 29, 29, 33, 37, 38, 45, 52, 55, 58, 61, 68, 70, 71, 73, 74, 77, 94, 95, 98}</syntaxhighlight> |
||
=={{header|Arendelle}}== |
=={{header|Arendelle}}== |
||
Line 794: | Line 794: | ||
=={{header|ARM Assembly}}== |
=={{header|ARM Assembly}}== |
||
{{works with|as|Raspberry Pi}} |
{{works with|as|Raspberry Pi}} |
||
<syntaxhighlight lang="arm assembly"> |
|||
<lang ARM Assembly> |
|||
/* ARM assembly Raspberry PI */ |
/* ARM assembly Raspberry PI */ |
||
Line 952: | Line 952: | ||
/***************************************************/ |
/***************************************************/ |
||
.include "../affichage.inc" |
.include "../affichage.inc" |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Arturo}}== |
=={{header|Arturo}}== |
||
< |
<syntaxhighlight lang="rebol">bubbleSort: function [items][ |
||
len: size items |
len: size items |
||
loop len [j][ |
loop len [j][ |
||
Line 971: | Line 971: | ||
] |
] |
||
print bubbleSort [3 1 2 8 5 7 9 4 6]</ |
print bubbleSort [3 1 2 8 5 7 9 4 6]</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 978: | Line 978: | ||
=={{header|AutoHotkey}}== |
=={{header|AutoHotkey}}== |
||
< |
<syntaxhighlight lang="autohotkey">var = |
||
( |
( |
||
dog |
dog |
||
Line 1,012: | Line 1,012: | ||
sorted .= array%A_Index% . "`n" |
sorted .= array%A_Index% . "`n" |
||
Return sorted |
Return sorted |
||
}</ |
}</syntaxhighlight> |
||
=={{header|AWK}}== |
=={{header|AWK}}== |
||
Sort the standard input and print it to standard output. |
Sort the standard input and print it to standard output. |
||
< |
<syntaxhighlight lang="awk">{ # read every line into an array |
||
line[NR] = $0 |
line[NR] = $0 |
||
} |
} |
||
Line 1,035: | Line 1,035: | ||
print line[i] |
print line[i] |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
GNU awk contains built in functions for sorting, but POSIX |
GNU awk contains built in functions for sorting, but POSIX |
||
Line 1,046: | Line 1,046: | ||
variables. |
variables. |
||
< |
<syntaxhighlight lang="awk"> |
||
# Test this example file from command line with: |
# Test this example file from command line with: |
||
# |
# |
||
Line 1,092: | Line 1,092: | ||
exit |
exit |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|bash}}== |
=={{header|bash}}== |
||
Line 1,098: | Line 1,098: | ||
I hope to see vastly improved versions of bubble_sort. |
I hope to see vastly improved versions of bubble_sort. |
||
< |
<syntaxhighlight lang="bash"> |
||
$ function bubble_sort() { |
$ function bubble_sort() { |
||
local a=("$@") |
local a=("$@") |
||
Line 1,139: | Line 1,139: | ||
-31 0 1 2 2 4 45 58 65 69 74 82 82 83 88 89 99 104 112 782 |
-31 0 1 2 2 4 45 58 65 69 74 82 82 83 88 89 99 104 112 782 |
||
$ |
$ |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|BASIC}}== |
=={{header|BASIC}}== |
||
Line 1,146: | Line 1,146: | ||
{{trans|Java}} |
{{trans|Java}} |
||
Assume numbers are in a DIM of size "size" called "nums". |
Assume numbers are in a DIM of size "size" called "nums". |
||
< |
<syntaxhighlight lang="qbasic"> |
||
DO |
DO |
||
changed = 0 |
changed = 0 |
||
Line 1,157: | Line 1,157: | ||
END IF |
END IF |
||
NEXT |
NEXT |
||
LOOP WHILE(NOT changed)</ |
LOOP WHILE(NOT changed)</syntaxhighlight> |
||
==={{header|Applesoft BASIC}}=== |
==={{header|Applesoft BASIC}}=== |
||
< |
<syntaxhighlight lang="basic">0 GOSUB 7 : IC = I%(0) |
||
1 FOR HC = -1 TO 0 |
1 FOR HC = -1 TO 0 |
||
2 LET IC = IC - 1 |
2 LET IC = IC - 1 |
||
Line 1,169: | Line 1,169: | ||
7 DIM I%(18000) : I%(0) = 50 |
7 DIM I%(18000) : I%(0) = 50 |
||
8 FOR I = 1 TO I%(0) : I%(I) = INT (RND(1) * 65535) - 32767 : NEXT |
8 FOR I = 1 TO I%(0) : I%(I) = INT (RND(1) * 65535) - 32767 : NEXT |
||
9 FOR I = 1 TO I%(0) : PRINT I%(I)" "; : NEXT I : PRINT : RETURN</ |
9 FOR I = 1 TO I%(0) : PRINT I%(I)" "; : NEXT I : PRINT : RETURN</syntaxhighlight> |
||
==={{header|Sinclair ZX81 BASIC}}=== |
==={{header|Sinclair ZX81 BASIC}}=== |
||
Works with the 1k RAM model. For simplicity, and to make it easy to animate the sort as it is going on, this implementation sorts a string of eight-bit unsigned integers which can be treated as character codes; it could easily be amended to sort an array of numbers or an array of strings, but the array would need to be dimensioned at the start. |
Works with the 1k RAM model. For simplicity, and to make it easy to animate the sort as it is going on, this implementation sorts a string of eight-bit unsigned integers which can be treated as character codes; it could easily be amended to sort an array of numbers or an array of strings, but the array would need to be dimensioned at the start. |
||
< |
<syntaxhighlight lang="basic"> 10 LET S$="FIRE BURN AND CAULDRON BUBBLE" |
||
20 PRINT S$ |
20 PRINT S$ |
||
30 LET L=LEN S$-1 |
30 LET L=LEN S$-1 |
||
Line 1,186: | Line 1,186: | ||
120 NEXT I |
120 NEXT I |
||
130 LET L=L-1 |
130 LET L=L-1 |
||
140 IF C THEN GOTO 40</ |
140 IF C THEN GOTO 40</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> AABBBBCDDEEFILLNNNORRRUUU</pre> |
<pre> AABBBBCDDEEFILLNNNORRRUUU</pre> |
||
Line 1,192: | Line 1,192: | ||
==={{header|BASIC256}}=== |
==={{header|BASIC256}}=== |
||
{{works with|BASIC256 }} |
{{works with|BASIC256 }} |
||
< |
<syntaxhighlight lang="basic256"> |
||
Dim a(11): ordered=false |
Dim a(11): ordered=false |
||
print "Original set" |
print "Original set" |
||
Line 1,217: | Line 1,217: | ||
print a[n]+", "; |
print a[n]+", "; |
||
next n |
next n |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}}(example) |
{{out}}(example) |
||
<pre> |
<pre> |
||
Line 1,228: | Line 1,228: | ||
==={{header|BBC BASIC}}=== |
==={{header|BBC BASIC}}=== |
||
The Bubble sort is very inefficient for 99% of cases. This routine uses a couple of 'tricks' to try and mitigate the inefficiency to a limited extent. Note that the array index is assumed to start at zero. |
The Bubble sort is very inefficient for 99% of cases. This routine uses a couple of 'tricks' to try and mitigate the inefficiency to a limited extent. Note that the array index is assumed to start at zero. |
||
< |
<syntaxhighlight lang="bbcbasic"> DIM test(9) |
||
test() = 4, 65, 2, -31, 0, 99, 2, 83, 782, 1 |
test() = 4, 65, 2, -31, 0, 99, 2, 83, 782, 1 |
||
PROCbubblesort(test(), 10) |
PROCbubblesort(test(), 10) |
||
Line 1,249: | Line 1,249: | ||
n% = l% |
n% = l% |
||
UNTIL l% = 0 |
UNTIL l% = 0 |
||
ENDPROC</ |
ENDPROC</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,257: | Line 1,257: | ||
==={{header|Commodore BASIC}}=== |
==={{header|Commodore BASIC}}=== |
||
<syntaxhighlight lang="commodore"> |
|||
<lang COMMODORE> |
|||
5 REM =============================================== |
5 REM =============================================== |
||
10 REM HTTP://ROSETTACODE.ORG/ |
10 REM HTTP://ROSETTACODE.ORG/ |
||
Line 1,305: | Line 1,305: | ||
910 DATA 15 |
910 DATA 15 |
||
920 DATA 64,34,25,12,22,11,90,13,59,47,19,89,10,17,31 |
920 DATA 64,34,25,12,22,11,90,13,59,47,19,89,10,17,31 |
||
</syntaxhighlight> |
|||
</lang> |
|||
==={{header|GW-BASIC}}=== |
==={{header|GW-BASIC}}=== |
||
< |
<syntaxhighlight lang="gwbasic">10 REM GENERATE A RANDOM BUNCH OF INTEGERS |
||
20 DIM ARR(20) |
20 DIM ARR(20) |
||
30 RANDOMIZE TIMER |
30 RANDOMIZE TIMER |
||
Line 1,331: | Line 1,331: | ||
1020 ARR(I+1) = TEMP |
1020 ARR(I+1) = TEMP |
||
1030 CHANGED = 1 |
1030 CHANGED = 1 |
||
1040 RETURN</ |
1040 RETURN</syntaxhighlight> |
||
{{out}}<pre> |
{{out}}<pre> |
||
20 59 42 9 5 91 6 64 21 28 65 96 20 66 66 70 91 98 63 31 |
20 59 42 9 5 91 6 64 21 28 65 96 20 66 66 70 91 98 63 31 |
||
Line 1,349: | Line 1,349: | ||
==={{header|IS-BASIC}}=== |
==={{header|IS-BASIC}}=== |
||
< |
<syntaxhighlight lang="is-basic">100 PROGRAM "BubblSrt.bas" |
||
110 RANDOMIZE |
110 RANDOMIZE |
||
120 NUMERIC ARRAY(-5 TO 9) |
120 NUMERIC ARRAY(-5 TO 9) |
||
Line 1,374: | Line 1,374: | ||
330 NEXT |
330 NEXT |
||
340 LOOP WHILE CH |
340 LOOP WHILE CH |
||
350 END DEF</ |
350 END DEF</syntaxhighlight> |
||
==={{header|BaCon}}=== |
==={{header|BaCon}}=== |
||
Numeric example: |
Numeric example: |
||
< |
<syntaxhighlight lang="bacon">LOCAL t[] = { 5, 7, 1, 3, 10, 2, 9, 4, 8, 6 } |
||
total = 10 |
total = 10 |
||
WHILE total > 1 |
WHILE total > 1 |
||
Line 1,386: | Line 1,386: | ||
DECR total |
DECR total |
||
WEND |
WEND |
||
PRINT COIL$(10, STR$(t[_-1]))</ |
PRINT COIL$(10, STR$(t[_-1]))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>1 2 3 4 5 6 7 8 9 10</pre> |
<pre>1 2 3 4 5 6 7 8 9 10</pre> |
||
String example: |
String example: |
||
< |
<syntaxhighlight lang="bacon">t$ = "Kiev Amsterdam Lima Moscow Warschau Vienna Paris Madrid Bonn Bern Rome" |
||
total = AMOUNT(t$) |
total = AMOUNT(t$) |
||
WHILE total > 1 |
WHILE total > 1 |
||
Line 1,398: | Line 1,398: | ||
DECR total |
DECR total |
||
WEND |
WEND |
||
PRINT t$</ |
PRINT t$</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>Amsterdam Bern Bonn Kiev Lima Madrid Moscow Paris Rome Vienna Warschau</pre> |
<pre>Amsterdam Bern Bonn Kiev Lima Madrid Moscow Paris Rome Vienna Warschau</pre> |
||
=={{header|BCPL}}== |
=={{header|BCPL}}== |
||
< |
<syntaxhighlight lang="bcpl">get "libhdr" |
||
let bubblesort(v, length) be |
let bubblesort(v, length) be |
||
Line 1,425: | Line 1,425: | ||
for i=0 to 9 do writef("%N ", v!i) |
for i=0 to 9 do writef("%N ", v!i) |
||
wrch('*N') |
wrch('*N') |
||
$)</ |
$)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>1 2 3 4 5 6 7 8 9 10</pre> |
<pre>1 2 3 4 5 6 7 8 9 10</pre> |
||
=={{header|C}}== |
=={{header|C}}== |
||
< |
<syntaxhighlight lang="c">#include <stdio.h> |
||
void bubble_sort (int *a, int n) { |
void bubble_sort (int *a, int n) { |
||
Line 1,459: | Line 1,459: | ||
return 0; |
return 0; |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,468: | Line 1,468: | ||
=={{header|C sharp|C#}}== |
=={{header|C sharp|C#}}== |
||
{{works with|C sharp|C#|3.0+}} |
{{works with|C sharp|C#|3.0+}} |
||
< |
<syntaxhighlight lang="csharp">using System; |
||
using System.Collections.Generic; |
using System.Collections.Generic; |
||
Line 1,511: | Line 1,511: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|C++}}== |
=={{header|C++}}== |
||
Uses C++11. Compile with |
Uses C++11. Compile with |
||
g++ -std=c++11 bubble.cpp |
g++ -std=c++11 bubble.cpp |
||
< |
<syntaxhighlight lang="cpp">#include <algorithm> |
||
#include <iostream> |
#include <iostream> |
||
#include <iterator> |
#include <iterator> |
||
Line 1,539: | Line 1,539: | ||
copy(std::begin(a), std::end(a), std::ostream_iterator<int>(std::cout, " ")); |
copy(std::begin(a), std::end(a), std::ostream_iterator<int>(std::cout, " ")); |
||
std::cout << "\n"; |
std::cout << "\n"; |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,548: | Line 1,548: | ||
Bubble sorts a Java ArrayList in place. Uses 'doseq' iteration construct with a short-circuit when a pass didn't produce any change, and within the pass, an atomic 'changed' variable that gets reset whenever a change occurs. |
Bubble sorts a Java ArrayList in place. Uses 'doseq' iteration construct with a short-circuit when a pass didn't produce any change, and within the pass, an atomic 'changed' variable that gets reset whenever a change occurs. |
||
< |
<syntaxhighlight lang="clojure">(ns bubblesort |
||
(:import java.util.ArrayList)) |
(:import java.util.ArrayList)) |
||
Line 1,574: | Line 1,574: | ||
arr))) |
arr))) |
||
(println (bubble-sort (ArrayList. [10 9 8 7 6 5 4 3 2 1])))</ |
(println (bubble-sort (ArrayList. [10 9 8 7 6 5 4 3 2 1])))</syntaxhighlight> |
||
Purely functional version working on Clojure sequences: |
Purely functional version working on Clojure sequences: |
||
< |
<syntaxhighlight lang="clojure">(defn- bubble-step |
||
"was-changed: whether any elements prior to the current first element |
"was-changed: whether any elements prior to the current first element |
||
were swapped; |
were swapped; |
||
Line 1,603: | Line 1,603: | ||
(recur less? result))))) |
(recur less? result))))) |
||
(println (bubble-sort [10 9 8 7 6 5 4 3 2 1]))</ |
(println (bubble-sort [10 9 8 7 6 5 4 3 2 1]))</syntaxhighlight> |
||
=={{header|CLU}}== |
=={{header|CLU}}== |
||
< |
<syntaxhighlight lang="clu">% Bubble-sort an array in place. |
||
bubble_sort = proc [T: type] (a: array[T]) |
bubble_sort = proc [T: type] (a: array[T]) |
||
where T has lt: proctype (T,T) returns (bool) |
where T has lt: proctype (T,T) returns (bool) |
||
Line 1,641: | Line 1,641: | ||
bubble_sort[int](test) |
bubble_sort[int](test) |
||
stream$puts(po, "After: ") print_arr[int](test, 3, po) |
stream$puts(po, "After: ") print_arr[int](test, 3, po) |
||
end start_up</ |
end start_up</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>Before: 7 -5 0 2 99 16 4 20 47 19 |
<pre>Before: 7 -5 0 2 99 16 4 20 47 19 |
||
Line 1,649: | Line 1,649: | ||
Only for lists of integers. |
Only for lists of integers. |
||
< |
<syntaxhighlight lang="cmake"># bubble_sort(var [value1 value2...]) sorts a list of integers. |
||
function(bubble_sort var) |
function(bubble_sort var) |
||
math(EXPR last "${ARGC} - 1") # Prepare to sort ARGV[1]..ARGV[last]. |
math(EXPR last "${ARGC} - 1") # Prepare to sort ARGV[1]..ARGV[last]. |
||
Line 1,674: | Line 1,674: | ||
endforeach(index) |
endforeach(index) |
||
set("${var}" "${answer}" PARENT_SCOPE) |
set("${var}" "${answer}" PARENT_SCOPE) |
||
endfunction(bubble_sort)</ |
endfunction(bubble_sort)</syntaxhighlight> |
||
< |
<syntaxhighlight lang="cmake">bubble_sort(result 33 11 44 22 66 55) |
||
message(STATUS "${result}")</ |
message(STATUS "${result}")</syntaxhighlight> |
||
<pre>-- 11;22;33;44;55;66</pre> |
<pre>-- 11;22;33;44;55;66</pre> |
||
Line 1,684: | Line 1,684: | ||
This is a complete program that demonstrates the bubble sort algorithm in COBOL. |
This is a complete program that demonstrates the bubble sort algorithm in COBOL. |
||
<br/>This version is for COBOL-74 which does not have in-line performs, nor END-IF and related constructs. |
<br/>This version is for COBOL-74 which does not have in-line performs, nor END-IF and related constructs. |
||
< |
<syntaxhighlight lang="cobol"> |
||
IDENTIFICATION DIVISION. |
IDENTIFICATION DIVISION. |
||
PROGRAM-ID. BUBBLESORT. |
PROGRAM-ID. BUBBLESORT. |
||
Line 1,830: | Line 1,830: | ||
F-999. |
F-999. |
||
EXIT. |
EXIT. |
||
</syntaxhighlight> |
|||
</lang> |
|||
A more modern version of COBOL. |
A more modern version of COBOL. |
||
< |
<syntaxhighlight lang="cobol"> |
||
identification division. |
identification division. |
||
program-id. BUBBLSRT. |
program-id. BUBBLSRT. |
||
Line 1,888: | Line 1,888: | ||
end-perform |
end-perform |
||
. |
. |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
Line 1,895: | Line 1,895: | ||
=={{header|Common Lisp}}== |
=={{header|Common Lisp}}== |
||
Bubble sort an sequence in-place, using the < operator for comparison if no comaprison function is provided |
Bubble sort an sequence in-place, using the < operator for comparison if no comaprison function is provided |
||
< |
<syntaxhighlight lang="lisp">(defun bubble-sort (sequence &optional (compare #'<)) |
||
"sort a sequence (array or list) with an optional comparison function (cl:< is the default)" |
"sort a sequence (array or list) with an optional comparison function (cl:< is the default)" |
||
(loop with sorted = nil until sorted do |
(loop with sorted = nil until sorted do |
||
Line 1,904: | Line 1,904: | ||
(rotatef (elt sequence a) |
(rotatef (elt sequence a) |
||
(elt sequence (1+ a))) |
(elt sequence (1+ a))) |
||
(setf sorted nil)))))</ |
(setf sorted nil)))))</syntaxhighlight> |
||
< |
<syntaxhighlight lang="lisp">(bubble-sort (list 5 4 3 2 1))</syntaxhighlight> |
||
<code>elt</code> has linear access time for lists, making the prior implementation of bubble-sort very expensive (although very clear, and straightforward to code. Here is an implementation that works efficiently for both vectors and lists. For lists it also has the nice property that the input list and the sorted list begin with the same <code>cons</code> cell. |
<code>elt</code> has linear access time for lists, making the prior implementation of bubble-sort very expensive (although very clear, and straightforward to code. Here is an implementation that works efficiently for both vectors and lists. For lists it also has the nice property that the input list and the sorted list begin with the same <code>cons</code> cell. |
||
< |
<syntaxhighlight lang="lisp">(defun bubble-sort-vector (vector predicate &aux (len (1- (length vector)))) |
||
(do ((swapped t)) ((not swapped) vector) |
(do ((swapped t)) ((not swapped) vector) |
||
(setf swapped nil) |
(setf swapped nil) |
||
Line 1,929: | Line 1,929: | ||
(etypecase sequence |
(etypecase sequence |
||
(list (bubble-sort-list sequence predicate)) |
(list (bubble-sort-list sequence predicate)) |
||
(vector (bubble-sort-vector sequence predicate))))</ |
(vector (bubble-sort-vector sequence predicate))))</syntaxhighlight> |
||
=={{header|Cowgol}}== |
=={{header|Cowgol}}== |
||
< |
<syntaxhighlight lang="cowgol">include "cowgol.coh"; |
||
# Comparator interface, on the model of C, i.e: |
# Comparator interface, on the model of C, i.e: |
||
Line 1,987: | Line 1,987: | ||
i := i + 1; |
i := i + 1; |
||
end loop; |
end loop; |
||
print_nl();</ |
print_nl();</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,994: | Line 1,994: | ||
=={{header|D}}== |
=={{header|D}}== |
||
< |
<syntaxhighlight lang="d">import std.stdio, std.algorithm : swap; |
||
T[] bubbleSort(T)(T[] data) pure nothrow |
T[] bubbleSort(T)(T[] data) pure nothrow |
||
Line 2,017: | Line 2,017: | ||
auto array = [28, 44, 46, 24, 19, 2, 17, 11, 25, 4]; |
auto array = [28, 44, 46, 24, 19, 2, 17, 11, 25, 4]; |
||
writeln(array.bubbleSort()); |
writeln(array.bubbleSort()); |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>[2, 4, 11, 17, 19, 24, 25, 28, 44, 46]</pre> |
<pre>[2, 4, 11, 17, 19, 24, 25, 28, 44, 46]</pre> |
||
Line 2,047: | Line 2,047: | ||
Static array is an arbitrary-based array of fixed length |
Static array is an arbitrary-based array of fixed length |
||
< |
<syntaxhighlight lang="delphi">program TestBubbleSort; |
||
{$APPTYPE CONSOLE} |
{$APPTYPE CONSOLE} |
||
Line 2,100: | Line 2,100: | ||
Writeln; |
Writeln; |
||
Readln; |
Readln; |
||
end.</ |
end.</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,108: | Line 2,108: | ||
=={{header|Draco}}== |
=={{header|Draco}}== |
||
< |
<syntaxhighlight lang="draco">/* Bubble sort an array of integers */ |
||
proc nonrec bubblesort([*] int a) void: |
proc nonrec bubblesort([*] int a) void: |
||
bool sorted; |
bool sorted; |
||
Line 2,138: | Line 2,138: | ||
write("After sorting: "); |
write("After sorting: "); |
||
for i from 0 upto 9 do write(a[i]:5) od |
for i from 0 upto 9 do write(a[i]:5) od |
||
corp</ |
corp</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>Before sorting: 9 -5 3 3 24 -16 3 -120 250 17 |
<pre>Before sorting: 9 -5 3 3 24 -16 3 -120 250 17 |
||
Line 2,145: | Line 2,145: | ||
=={{header|Dyalect}}== |
=={{header|Dyalect}}== |
||
< |
<syntaxhighlight lang="dyalect">func bubbleSort(list) { |
||
var done = false |
var done = false |
||
while !done { |
while !done { |
||
Line 2,162: | Line 2,162: | ||
var xs = [3,1,5,4,2,6] |
var xs = [3,1,5,4,2,6] |
||
bubbleSort(xs) |
bubbleSort(xs) |
||
print(xs)</ |
print(xs)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,169: | Line 2,169: | ||
=={{header|E}}== |
=={{header|E}}== |
||
< |
<syntaxhighlight lang="e">def bubbleSort(target) { |
||
__loop(fn { |
__loop(fn { |
||
var changed := false |
var changed := false |
||
Line 2,181: | Line 2,181: | ||
changed |
changed |
||
}) |
}) |
||
}</ |
}</syntaxhighlight> |
||
(Uses the primitive __loop directly because it happens to map to the termination test for this algorithm well.) |
(Uses the primitive __loop directly because it happens to map to the termination test for this algorithm well.) |
||
=={{header|EchoLisp}}== |
=={{header|EchoLisp}}== |
||
< |
<syntaxhighlight lang="scheme"> |
||
;; sorts a vector of objects in place |
;; sorts a vector of objects in place |
||
;; proc is an user defined comparison procedure |
;; proc is an user defined comparison procedure |
||
Line 2,203: | Line 2,203: | ||
(bubble-sort V sort/length) |
(bubble-sort V sort/length) |
||
→ #(zen simon elvis albert antoinette) |
→ #(zen simon elvis albert antoinette) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|EDSAC order code}}== |
=={{header|EDSAC order code}}== |
||
Line 2,212: | Line 2,212: | ||
To clarify the EDSAC program, an equivalent Pascal program is added as a comment. |
To clarify the EDSAC program, an equivalent Pascal program is added as a comment. |
||
< |
<syntaxhighlight lang="edsac"> |
||
[Bubble sort demo for Rosetta Code website] |
[Bubble sort demo for Rosetta Code website] |
||
[EDSAC program. Initial Orders 2] |
[EDSAC program. Initial Orders 2] |
||
Line 2,364: | Line 2,364: | ||
E 14 Z [define entry point] |
E 14 Z [define entry point] |
||
P F [acc = 0 on entry] |
P F [acc = 0 on entry] |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,384: | Line 2,384: | ||
This solution is presented in two classes. The first is a simple application that creates a set, an instance of <code lang="eiffel">MY_SORTED_SET</code>, and adds elements to the set in unsorted order. It iterates across the set printing the elements, then it sorts the set, and reprints the elements. |
This solution is presented in two classes. The first is a simple application that creates a set, an instance of <code lang="eiffel">MY_SORTED_SET</code>, and adds elements to the set in unsorted order. It iterates across the set printing the elements, then it sorts the set, and reprints the elements. |
||
< |
<syntaxhighlight lang="eiffel">class |
||
APPLICATION |
APPLICATION |
||
create |
create |
||
Line 2,413: | Line 2,413: | ||
my_set: MY_SORTED_SET [INTEGER] |
my_set: MY_SORTED_SET [INTEGER] |
||
-- Set to be sorted |
-- Set to be sorted |
||
end</ |
end</syntaxhighlight> |
||
The second class is <code lang="eiffel">MY_SORTED_SET</code>. |
The second class is <code lang="eiffel">MY_SORTED_SET</code>. |
||
< |
<syntaxhighlight lang="eiffel">class |
||
MY_SORTED_SET [G -> COMPARABLE] |
MY_SORTED_SET [G -> COMPARABLE] |
||
inherit |
inherit |
||
Line 2,452: | Line 2,452: | ||
end |
end |
||
end |
end |
||
end</ |
end</syntaxhighlight> |
||
This class inherits from the Eiffel library class <code lang="eiffel">TWO_WAY_SORTED_SET</code>, which implements sets whose elements are comparable. Therefore, the set can be ordered and in fact is kept so under normal circumstances. |
This class inherits from the Eiffel library class <code lang="eiffel">TWO_WAY_SORTED_SET</code>, which implements sets whose elements are comparable. Therefore, the set can be ordered and in fact is kept so under normal circumstances. |
||
Line 2,473: | Line 2,473: | ||
{{trans|C#}} |
{{trans|C#}} |
||
ELENA 5.0 : |
ELENA 5.0 : |
||
< |
<syntaxhighlight lang="elena">import system'routines; |
||
import extensions; |
import extensions; |
||
Line 2,506: | Line 2,506: | ||
var list := new int[]{3, 7, 3, 2, 1, -4, 10, 12, 4}; |
var list := new int[]{3, 7, 3, 2, 1, -4, 10, 12, 4}; |
||
console.printLine(list.bubbleSort().asEnumerable()) |
console.printLine(list.bubbleSort().asEnumerable()) |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,513: | Line 2,513: | ||
=={{header|Elixir}}== |
=={{header|Elixir}}== |
||
< |
<syntaxhighlight lang="elixir">defmodule Sort do |
||
def bsort(list) when is_list(list) do |
def bsort(list) when is_list(list) do |
||
t = bsort_iter(list) |
t = bsort_iter(list) |
||
Line 2,523: | Line 2,523: | ||
def bsort_iter([x, y | t]), do: [x | bsort_iter([y | t])] |
def bsort_iter([x, y | t]), do: [x | bsort_iter([y | t])] |
||
def bsort_iter(list), do: list |
def bsort_iter(list), do: list |
||
end</ |
end</syntaxhighlight> |
||
=={{header|Erlang}}== |
=={{header|Erlang}}== |
||
sort/3 copied from Stackoverflow. |
sort/3 copied from Stackoverflow. |
||
<syntaxhighlight lang="erlang"> |
|||
<lang Erlang> |
|||
-module( bubble_sort ). |
-module( bubble_sort ). |
||
Line 2,544: | Line 2,544: | ||
sort( [X, Y | T], Acc, _Done ) when X > Y -> sort( [X | T], [Y | Acc], false ); |
sort( [X, Y | T], Acc, _Done ) when X > Y -> sort( [X | T], [Y | Acc], false ); |
||
sort( [X | T], Acc, Done ) -> sort( T, [X | Acc], Done ). |
sort( [X | T], Acc, Done ) -> sort( T, [X | Acc], Done ). |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,552: | Line 2,552: | ||
=={{header|ERRE}}== |
=={{header|ERRE}}== |
||
<syntaxhighlight lang="erre"> |
|||
<lang ERRE> |
|||
PROGRAM BUBBLE_SORT |
PROGRAM BUBBLE_SORT |
||
Line 2,584: | Line 2,584: | ||
PRINT |
PRINT |
||
END PROGRAM |
END PROGRAM |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Euphoria}}== |
=={{header|Euphoria}}== |
||
< |
<syntaxhighlight lang="euphoria">function bubble_sort(sequence s) |
||
object tmp |
object tmp |
||
integer changed |
integer changed |
||
Line 2,613: | Line 2,613: | ||
pretty_print(1,s,{2}) |
pretty_print(1,s,{2}) |
||
puts(1,"\nAfter: ") |
puts(1,"\nAfter: ") |
||
pretty_print(1,bubble_sort(s),{2})</ |
pretty_print(1,bubble_sort(s),{2})</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,650: | Line 2,650: | ||
=={{header|Ezhil}}== |
=={{header|Ezhil}}== |
||
<syntaxhighlight lang="ezhil"> |
|||
<lang Ezhil> |
|||
## இந்த நிரல் ஒரு பட்டியலில் உள்ள எண்களை Bubble Sort என்ற முறைப்படி ஏறுவரிசையிலும் பின்னர் அதையே இறங்குவரிசையிலும் அடுக்கித் தரும் |
## இந்த நிரல் ஒரு பட்டியலில் உள்ள எண்களை Bubble Sort என்ற முறைப்படி ஏறுவரிசையிலும் பின்னர் அதையே இறங்குவரிசையிலும் அடுக்கித் தரும் |
||
Line 2,718: | Line 2,718: | ||
பதிப்பி எண்கள்பிரதி |
பதிப்பி எண்கள்பிரதி |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|F Sharp|F#}}== |
=={{header|F Sharp|F#}}== |
||
< |
<syntaxhighlight lang="fsharp">let BubbleSort (lst : list<int>) = |
||
let rec sort accum rev lst = |
let rec sort accum rev lst = |
||
match lst, rev with |
match lst, rev with |
||
Line 2,729: | Line 2,729: | ||
| head::tail, _ -> sort (head::accum) rev tail |
| head::tail, _ -> sort (head::accum) rev tail |
||
sort [] true lst |
sort [] true lst |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Factor}}== |
=={{header|Factor}}== |
||
< |
<syntaxhighlight lang="factor">USING: fry kernel locals math math.order sequences |
||
sequences.private ; |
sequences.private ; |
||
IN: rosetta.bubble |
IN: rosetta.bubble |
||
Line 2,754: | Line 2,754: | ||
: natural-sort! ( seq -- ) |
: natural-sort! ( seq -- ) |
||
[ <=> ] sort! ;</ |
[ <=> ] sort! ;</syntaxhighlight> |
||
It is possible to pass your own comparison operator to <code>sort!</code>, so you can f.e. sort your sequence backwards with passing <code>[ >=< ]</code> into it. |
It is possible to pass your own comparison operator to <code>sort!</code>, so you can f.e. sort your sequence backwards with passing <code>[ >=< ]</code> into it. |
||
< |
<syntaxhighlight lang="factor">10 [ 10000 random ] replicate |
||
[ "Before: " write . ] |
[ "Before: " write . ] |
||
[ "Natural: " write [ natural-sort! ] keep . ] |
[ "Natural: " write [ natural-sort! ] keep . ] |
||
[ "Reverse: " write [ [ >=< ] sort! ] keep . ] tri</ |
[ "Reverse: " write [ [ >=< ] sort! ] keep . ] tri</syntaxhighlight> |
||
Before: { 3707 5045 4661 1489 3140 7195 8844 6506 6322 3199 } |
Before: { 3707 5045 4661 1489 3140 7195 8844 6506 6322 3199 } |
||
Line 2,770: | Line 2,770: | ||
This is not a complete implementation of bubblesort: it doesn't keep a boolean flag whether to stop, so it goes on printing each stage of the sorting process ad infinitum. |
This is not a complete implementation of bubblesort: it doesn't keep a boolean flag whether to stop, so it goes on printing each stage of the sorting process ad infinitum. |
||
< |
<syntaxhighlight lang="fish">v Sorts the (pre-loaded) stack |
||
with bubblesort. |
with bubblesort. |
||
v < |
v < |
||
Line 2,777: | Line 2,777: | ||
>~{ao ^ |
>~{ao ^ |
||
>~}l &{ v |
>~}l &{ v |
||
o","{n:&-1^?=0:&<</ |
o","{n:&-1^?=0:&<</syntaxhighlight> |
||
=={{header|Forth}}== |
=={{header|Forth}}== |
||
Sorts the 'cnt' cells stored at 'addr' using the test stored in the deferred word 'bubble-test'. Uses forth local variables for clarity. |
Sorts the 'cnt' cells stored at 'addr' using the test stored in the deferred word 'bubble-test'. Uses forth local variables for clarity. |
||
< |
<syntaxhighlight lang="forth">defer bubble-test |
||
' > is bubble-test |
' > is bubble-test |
||
Line 2,790: | Line 2,790: | ||
i 2@ bubble-test if i 2@ swap i 2! then |
i 2@ bubble-test if i 2@ swap i 2! then |
||
cell +loop |
cell +loop |
||
loop ;</ |
loop ;</syntaxhighlight> |
||
This is the same algorithm done without the local variables: |
This is the same algorithm done without the local variables: |
||
< |
<syntaxhighlight lang="forth">: bubble ( addr cnt -- ) |
||
dup 1 do |
dup 1 do |
||
2dup i - cells bounds do |
2dup i - cells bounds do |
||
i 2@ bubble-test if i 2@ swap i 2! then |
i 2@ bubble-test if i 2@ swap i 2! then |
||
cell +loop |
cell +loop |
||
loop ;</ |
loop ;</syntaxhighlight> |
||
Version with ''O(n)'' best case: |
Version with ''O(n)'' best case: |
||
< |
<syntaxhighlight lang="forth">: bubble ( addr len -- ) |
||
begin |
begin |
||
1- 2dup true -rot ( sorted addr len-1 ) |
1- 2dup true -rot ( sorted addr len-1 ) |
||
Line 2,811: | Line 2,811: | ||
then |
then |
||
cell +loop ( sorted ) |
cell +loop ( sorted ) |
||
until 2drop ;</ |
until 2drop ;</syntaxhighlight> |
||
Test any version with this: |
Test any version with this: |
||
Line 2,827: | Line 2,827: | ||
=={{header|Fortran}}== |
=={{header|Fortran}}== |
||
< |
<syntaxhighlight lang="fortran">SUBROUTINE Bubble_Sort(a) |
||
REAL, INTENT(in out), DIMENSION(:) :: a |
REAL, INTENT(in out), DIMENSION(:) :: a |
||
REAL :: temp |
REAL :: temp |
||
Line 2,845: | Line 2,845: | ||
IF (.NOT. swapped) EXIT |
IF (.NOT. swapped) EXIT |
||
END DO |
END DO |
||
END SUBROUTINE Bubble_Sort</ |
END SUBROUTINE Bubble_Sort</syntaxhighlight> |
||
=={{header|FreeBASIC}}== |
=={{header|FreeBASIC}}== |
||
Per task pseudo code: |
Per task pseudo code: |
||
< |
<syntaxhighlight lang="freebasic">' version 21-10-2016 |
||
' compile with: fbc -s console |
' compile with: fbc -s console |
||
' for boundry checks on array's compile with: fbc -s console -exx |
' for boundry checks on array's compile with: fbc -s console -exx |
||
Line 2,895: | Line 2,895: | ||
Print : Print "hit any key to end program" |
Print : Print "hit any key to end program" |
||
Sleep |
Sleep |
||
End</ |
End</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>unsort -7 3 -4 -6 4 -1 -2 2 7 0 5 1 -3 -5 6 |
<pre>unsort -7 3 -4 -6 4 -1 -2 2 7 0 5 1 -3 -5 6 |
||
Line 2,901: | Line 2,901: | ||
=={{header|g-fu}}== |
=={{header|g-fu}}== |
||
< |
<syntaxhighlight lang="g-fu"> |
||
(fun bubbles (vs) |
(fun bubbles (vs) |
||
(let done? F n (len vs)) |
(let done? F n (len vs)) |
||
Line 2,917: | Line 2,917: | ||
--- |
--- |
||
(1 2 3) |
(1 2 3) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Gambas}}== |
=={{header|Gambas}}== |
||
'''[https://gambas-playground.proko.eu/?gist=ba84832d633cb92bbe6c2f54704819c3 Click this link to run this code]''' |
'''[https://gambas-playground.proko.eu/?gist=ba84832d633cb92bbe6c2f54704819c3 Click this link to run this code]''' |
||
< |
<syntaxhighlight lang="gambas">Public Sub Main() |
||
Dim byToSort As Byte[] = [249, 28, 111, 36, 171, 98, 29, 448, 44, 147, 154, 46, 102, 183, 24, |
Dim byToSort As Byte[] = [249, 28, 111, 36, 171, 98, 29, 448, 44, 147, 154, 46, 102, 183, 24, |
||
120, 19, 123, 2, 17, 226, 11, 211, 25, 191, 205, 77] |
120, 19, 123, 2, 17, 226, 11, 211, 25, 191, 205, 77] |
||
Line 2,952: | Line 2,952: | ||
Print |
Print |
||
End</ |
End</syntaxhighlight> |
||
Output: |
Output: |
||
<pre> |
<pre> |
||
Line 2,982: | Line 2,982: | ||
=={{header|Go}}== |
=={{header|Go}}== |
||
Per task pseudocode: |
Per task pseudocode: |
||
< |
<syntaxhighlight lang="go">package main |
||
import "fmt" |
import "fmt" |
||
Line 3,007: | Line 3,007: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
More generic version that can sort anything that implements <code>sort.Interface</code>: |
More generic version that can sort anything that implements <code>sort.Interface</code>: |
||
< |
<syntaxhighlight lang="go">package main |
||
import ( |
import ( |
||
Line 3,038: | Line 3,038: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Groovy}}== |
=={{header|Groovy}}== |
||
Solution: |
Solution: |
||
< |
<syntaxhighlight lang="groovy">def makeSwap = { a, i, j = i+1 -> print "."; a[[i,j]] = a[[j,i]] } |
||
def checkSwap = { a, i, j = i+1 -> [(a[i] > a[j])].find { it }.each { makeSwap(a, i, j) } } |
def checkSwap = { a, i, j = i+1 -> [(a[i] > a[j])].find { it }.each { makeSwap(a, i, j) } } |
||
Line 3,050: | Line 3,050: | ||
while (swapped) { swapped = (1..<list.size()).any { checkSwap(list, it-1) } } |
while (swapped) { swapped = (1..<list.size()).any { checkSwap(list, it-1) } } |
||
list |
list |
||
}</ |
}</syntaxhighlight> |
||
Test Program: |
Test Program: |
||
< |
<syntaxhighlight lang="groovy">println bubbleSort([23,76,99,58,97,57,35,89,51,38,95,92,24,46,31,24,14,12,57,78,4]) |
||
println bubbleSort([88,18,31,44,4,0,8,81,14,78,20,76,84,33,73,75,82,5,62,70,12,7,1])</ |
println bubbleSort([88,18,31,44,4,0,8,81,14,78,20,76,84,33,73,75,82,5,62,70,12,7,1])</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 3,062: | Line 3,062: | ||
=={{header|Haskell}}== |
=={{header|Haskell}}== |
||
This version checks for changes in a separate step for simplicity, because Haskell has no variables to track them with. |
This version checks for changes in a separate step for simplicity, because Haskell has no variables to track them with. |
||
< |
<syntaxhighlight lang="haskell">bsort :: Ord a => [a] -> [a] |
||
bsort s = case _bsort s of |
bsort s = case _bsort s of |
||
t | t == s -> t |
t | t == s -> t |
||
Line 3,068: | Line 3,068: | ||
where _bsort (x:x2:xs) | x > x2 = x2:(_bsort (x:xs)) |
where _bsort (x:x2:xs) | x > x2 = x2:(_bsort (x:xs)) |
||
| otherwise = x:(_bsort (x2:xs)) |
| otherwise = x:(_bsort (x2:xs)) |
||
_bsort s = s</ |
_bsort s = s</syntaxhighlight> |
||
This version uses the polymorphic <tt>Maybe</tt> type to designate unchanged lists. (The type signature of <tt>_bsort</tt> is now <tt>Ord a => [a] -> Maybe [a]</tt>.) It is slightly faster than the previous one. |
This version uses the polymorphic <tt>Maybe</tt> type to designate unchanged lists. (The type signature of <tt>_bsort</tt> is now <tt>Ord a => [a] -> Maybe [a]</tt>.) It is slightly faster than the previous one. |
||
< |
<syntaxhighlight lang="haskell">import Data.Maybe (fromMaybe) |
||
import Control.Monad |
import Control.Monad |
||
Line 3,080: | Line 3,080: | ||
then Just $ x2 : fromMaybe (x:xs) (_bsort $ x:xs) |
then Just $ x2 : fromMaybe (x:xs) (_bsort $ x:xs) |
||
else liftM (x:) $ _bsort (x2:xs) |
else liftM (x:) $ _bsort (x2:xs) |
||
_bsort _ = Nothing</ |
_bsort _ = Nothing</syntaxhighlight> |
||
This version is based on the above, but avoids sorting the whole list each time. To implement this without a counter and retain using pattern matching, inner sorting is reversed, and then the result is reversed back. Sorting is based on a predicate, e.g., (<) or (>). |
This version is based on the above, but avoids sorting the whole list each time. To implement this without a counter and retain using pattern matching, inner sorting is reversed, and then the result is reversed back. Sorting is based on a predicate, e.g., (<) or (>). |
||
< |
<syntaxhighlight lang="haskell">import Data.Maybe (fromMaybe) |
||
import Control.Monad |
import Control.Monad |
||
Line 3,099: | Line 3,099: | ||
bsort :: Ord a => [a] -> [a] |
bsort :: Ord a => [a] -> [a] |
||
bsort = bubbleSortBy (<)</ |
bsort = bubbleSortBy (<)</syntaxhighlight> |
||
=={{header|Haxe}}== |
=={{header|Haxe}}== |
||
< |
<syntaxhighlight lang="haxe">class BubbleSort { |
||
@:generic |
@:generic |
||
public static function sort<T>(arr:Array<T>) { |
public static function sort<T>(arr:Array<T>) { |
||
Line 3,140: | Line 3,140: | ||
Sys.println('Sorted Strings: ' + stringArray); |
Sys.println('Sorted Strings: ' + stringArray); |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 3,153: | Line 3,153: | ||
=={{header|HicEst}}== |
=={{header|HicEst}}== |
||
< |
<syntaxhighlight lang="fortran">SUBROUTINE Bubble_Sort(a) |
||
REAL :: a(1) |
REAL :: a(1) |
||
Line 3,168: | Line 3,168: | ||
IF (swapped == 0) RETURN |
IF (swapped == 0) RETURN |
||
ENDDO |
ENDDO |
||
END</ |
END</syntaxhighlight> |
||
=={{header|Icon}} and {{header|Unicon}}== |
=={{header|Icon}} and {{header|Unicon}}== |
||
Icon/Unicon implementation of a bubble sort |
Icon/Unicon implementation of a bubble sort |
||
< |
<syntaxhighlight lang="icon">procedure main() #: demonstrate various ways to sort a list and string |
||
demosort(bubblesort,[3, 14, 1, 5, 9, 2, 6, 3],"qwerty") |
demosort(bubblesort,[3, 14, 1, 5, 9, 2, 6, 3],"qwerty") |
||
end |
end |
||
Line 3,187: | Line 3,187: | ||
X[i-1] :=: X[swapped := i] |
X[i-1] :=: X[swapped := i] |
||
return X |
return X |
||
end</ |
end</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 3,207: | Line 3,207: | ||
* 'demosort' can apply different sorting procedures and operators to lists and strings to show how this works. The routines 'displaysort' and 'writex' are helpers. |
* 'demosort' can apply different sorting procedures and operators to lists and strings to show how this works. The routines 'displaysort' and 'writex' are helpers. |
||
< |
<syntaxhighlight lang="icon">invocable all # for op |
||
procedure sortop(op,X) #: select how to sort |
procedure sortop(op,X) #: select how to sort |
||
Line 3,265: | Line 3,265: | ||
write() |
write() |
||
return |
return |
||
end</ |
end</syntaxhighlight> |
||
=={{header|Io}}== |
=={{header|Io}}== |
||
<syntaxhighlight lang="io"> |
|||
<lang Io> |
|||
List do( |
List do( |
||
bubblesort := method( |
bubblesort := method( |
||
Line 3,284: | Line 3,284: | ||
) |
) |
||
) |
) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|J}}== |
=={{header|J}}== |
||
{{eff note|J|/:~ list}} |
{{eff note|J|/:~ list}} |
||
< |
<syntaxhighlight lang="j">bubbleSort=: (([ (<. , >.) {.@]) , }.@])/^:_</syntaxhighlight> |
||
Test program: |
Test program: |
||
< |
<syntaxhighlight lang="j"> ?. 10 $ 10 |
||
4 6 8 6 5 8 6 6 6 9 |
4 6 8 6 5 8 6 6 6 9 |
||
bubbleSort ?. 10 $ 10 |
bubbleSort ?. 10 $ 10 |
||
4 5 6 6 6 6 6 8 8 9</ |
4 5 6 6 6 6 6 8 8 9</syntaxhighlight> |
||
For the most part, bubble sort works against J's strengths. However, once a single pass has been implemented as a list operation, <code>^:_</code> tells J to repeat this until the result stops changing. |
For the most part, bubble sort works against J's strengths. However, once a single pass has been implemented as a list operation, <code>^:_</code> tells J to repeat this until the result stops changing. |
||
=={{header|Janet}}== |
=={{header|Janet}}== |
||
< |
<syntaxhighlight lang="janet"> |
||
(defn bubble-sort! |
(defn bubble-sort! |
||
[arr] |
[arr] |
||
Line 3,326: | Line 3,326: | ||
) |
) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Java}}== |
=={{header|Java}}== |
||
Bubble sorting (ascending) an array of any <tt>Comparable</tt> type: |
Bubble sorting (ascending) an array of any <tt>Comparable</tt> type: |
||
< |
<syntaxhighlight lang="java">public static <E extends Comparable<? super E>> void bubbleSort(E[] comparable) { |
||
boolean changed = false; |
boolean changed = false; |
||
do { |
do { |
||
Line 3,343: | Line 3,343: | ||
} |
} |
||
} while (changed); |
} while (changed); |
||
}</ |
}</syntaxhighlight> |
||
For descending, simply switch the direction of comparison: |
For descending, simply switch the direction of comparison: |
||
< |
<syntaxhighlight lang="java">if (comparable[a].compareTo(comparable[b]) < 0){ |
||
//same swap code as before |
//same swap code as before |
||
}</ |
}</syntaxhighlight> |
||
=={{header|JavaScript}}== |
=={{header|JavaScript}}== |
||
< |
<syntaxhighlight lang="javascript">Array.prototype.bubblesort = function() { |
||
var done = false; |
var done = false; |
||
while (!done) { |
while (!done) { |
||
Line 3,363: | Line 3,363: | ||
} |
} |
||
return this; |
return this; |
||
}</ |
}</syntaxhighlight> |
||
{{works with|SEE|3.0}} |
{{works with|SEE|3.0}} |
||
{{works with|OSSP js|1.6.20070208}} |
{{works with|OSSP js|1.6.20070208}} |
||
< |
<syntaxhighlight lang="javascript">Array.prototype.bubblesort = function() { |
||
var done = false; |
var done = false; |
||
while (! done) { |
while (! done) { |
||
Line 3,381: | Line 3,381: | ||
} |
} |
||
return this; |
return this; |
||
}</ |
}</syntaxhighlight> |
||
Example: |
Example: |
||
< |
<syntaxhighlight lang="javascript">var my_arr = ["G", "F", "C", "A", "B", "E", "D"]; |
||
my_arr.bubblesort(); |
my_arr.bubblesort(); |
||
print(my_arr);</ |
print(my_arr);</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 3,394: | Line 3,394: | ||
webpage version (for the rest of us): |
webpage version (for the rest of us): |
||
< |
<syntaxhighlight lang="javascript"><script> |
||
Array.prototype.bubblesort = function() { |
Array.prototype.bubblesort = function() { |
||
var done = false; |
var done = false; |
||
Line 3,416: | Line 3,416: | ||
} |
} |
||
document.write(output); |
document.write(output); |
||
</script></ |
</script></syntaxhighlight> |
||
=={{header|jq}}== |
=={{header|jq}}== |
||
< |
<syntaxhighlight lang="jq">def bubble_sort: |
||
def swap(i;j): .[i] as $x | .[i]=.[j] | .[j]=$x; |
def swap(i;j): .[i] as $x | .[i]=.[j] | .[j]=$x; |
||
Line 3,432: | Line 3,432: | ||
else . |
else . |
||
end ) |
end ) |
||
end ) | .[1] ;</ |
end ) | .[1] ;</syntaxhighlight> |
||
'''Example''': |
'''Example''': |
||
< |
<syntaxhighlight lang="jq">( |
||
[3,2,1], |
[3,2,1], |
||
[1,2,3], |
[1,2,3], |
||
["G", "F", "C", "A", "B", "E", "D"] |
["G", "F", "C", "A", "B", "E", "D"] |
||
) | bubble_sort</ |
) | bubble_sort</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
< |
<syntaxhighlight lang="sh">$ jq -c -n -f Bubble_sort.jq |
||
[1,2,3] |
[1,2,3] |
||
[1,2,3] |
[1,2,3] |
||
["A","B","C","D","E","F","G"]</ |
["A","B","C","D","E","F","G"]</syntaxhighlight> |
||
=={{header|Julia}}== |
=={{header|Julia}}== |
||
{{works with|Julia|0.6}} |
{{works with|Julia|0.6}} |
||
< |
<syntaxhighlight lang="julia">function bubblesort!(arr::AbstractVector) |
||
for _ in 2:length(arr), j in 1:length(arr)-1 |
for _ in 2:length(arr), j in 1:length(arr)-1 |
||
if arr[j] > arr[j+1] |
if arr[j] > arr[j+1] |
||
Line 3,458: | Line 3,458: | ||
v = rand(-10:10, 10) |
v = rand(-10:10, 10) |
||
println("# unordered: $v\n -> ordered: ", bubblesort!(v))</ |
println("# unordered: $v\n -> ordered: ", bubblesort!(v))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 3,467: | Line 3,467: | ||
{{trans|Java}} |
{{trans|Java}} |
||
< |
<syntaxhighlight lang="scala">import java.util.Comparator |
||
fun <T> bubbleSort(a: Array<T>, c: Comparator<T>) { |
fun <T> bubbleSort(a: Array<T>, c: Comparator<T>) { |
||
Line 3,482: | Line 3,482: | ||
} |
} |
||
} while (changed) |
} while (changed) |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Lambdatalk}}== |
=={{header|Lambdatalk}}== |
||
< |
<syntaxhighlight lang="scheme"> |
||
{def bubblesort |
{def bubblesort |
||
{def bubblesort.swap! |
{def bubblesort.swap! |
||
Line 3,510: | Line 3,510: | ||
{bubblesort {A.new 0 3 86 20 27 67 31 16 37 42 8 47 7 84 5 29}} |
{bubblesort {A.new 0 3 86 20 27 67 31 16 37 42 8 47 7 84 5 29}} |
||
-> [0,3,5,7,8,16,20,27,29,31,37,42,47,67,84,86] |
-> [0,3,5,7,8,16,20,27,29,31,37,42,47,67,84,86] |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Liberty BASIC}}== |
=={{header|Liberty BASIC}}== |
||
<syntaxhighlight lang="lb"> |
|||
<lang lb> |
|||
itemCount = 20 |
itemCount = 20 |
||
dim item(itemCount) |
dim item(itemCount) |
||
Line 3,542: | Line 3,542: | ||
next i |
next i |
||
end |
end |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Lisaac}}== |
=={{header|Lisaac}}== |
||
< |
<syntaxhighlight lang="lisaac">Section Header |
||
+ name := BUBBLE_SORT; |
+ name := BUBBLE_SORT; |
||
Line 3,587: | Line 3,587: | ||
}; |
}; |
||
}.do_while {!sorted}; |
}.do_while {!sorted}; |
||
);</ |
);</syntaxhighlight> |
||
=={{header|Lua}}== |
=={{header|Lua}}== |
||
<syntaxhighlight lang="lua"> |
|||
<lang Lua> |
|||
function bubbleSort(A) |
function bubbleSort(A) |
||
local itemCount=#A |
local itemCount=#A |
||
Line 3,606: | Line 3,606: | ||
until hasChanged == false |
until hasChanged == false |
||
end |
end |
||
</syntaxhighlight> |
|||
</lang> |
|||
Example: |
Example: |
||
< |
<syntaxhighlight lang="lua"> |
||
list = { 5, 6, 1, 2, 9, 14, 2, 15, 6, 7, 8, 97 } |
list = { 5, 6, 1, 2, 9, 14, 2, 15, 6, 7, 8, 97 } |
||
bubbleSort(list) |
bubbleSort(list) |
||
Line 3,615: | Line 3,615: | ||
print(j) |
print(j) |
||
end |
end |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Lucid}}== |
=={{header|Lucid}}== |
||
[http://i.csc.uvic.ca/home/hei/lup/06.html] |
[http://i.csc.uvic.ca/home/hei/lup/06.html] |
||
< |
<syntaxhighlight lang="lucid">bsort(a) = if iseod(first a) then a else |
||
follow(bsort(allbutlast(b)),last(b)) fi |
follow(bsort(allbutlast(b)),last(b)) fi |
||
where |
where |
||
Line 3,634: | Line 3,634: | ||
last(x) = (x asa iseod next x) fby eod; |
last(x) = (x asa iseod next x) fby eod; |
||
allbutlast(x) = if not iseod(next x) then x else eod fi; |
allbutlast(x) = if not iseod(next x) then x else eod fi; |
||
end</ |
end</syntaxhighlight> |
||
=={{header|M2000 Interpreter}}== |
=={{header|M2000 Interpreter}}== |
||
Line 3,642: | Line 3,642: | ||
<syntaxhighlight lang="m2000 interpreter"> |
|||
<lang M2000 Interpreter> |
|||
Module Bubble { |
Module Bubble { |
||
function bubblesort { |
function bubblesort { |
||
Line 3,687: | Line 3,687: | ||
} |
} |
||
Bubble |
Bubble |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|M4}}== |
=={{header|M4}}== |
||
< |
<syntaxhighlight lang="m4">divert(-1) |
||
define(`randSeed',141592653) |
define(`randSeed',141592653) |
||
Line 3,734: | Line 3,734: | ||
show(`a') |
show(`a') |
||
bubblesort(`a') |
bubblesort(`a') |
||
show(`a')</ |
show(`a')</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 3,742: | Line 3,742: | ||
=={{header|Maple}}== |
=={{header|Maple}}== |
||
<lang>arr := Array([17,3,72,0,36,2,3,8,40,0]): |
<syntaxhighlight lang="text">arr := Array([17,3,72,0,36,2,3,8,40,0]): |
||
len := numelems(arr): |
len := numelems(arr): |
||
while(true) do |
while(true) do |
||
Line 3,757: | Line 3,757: | ||
if (not change) then break end if: |
if (not change) then break end if: |
||
end do: |
end do: |
||
arr;</ |
arr;</syntaxhighlight> |
||
{{Out|Output}} |
{{Out|Output}} |
||
<pre>[0,0,2,3,3,8,17,36,40,72]</pre> |
<pre>[0,0,2,3,3,8,17,36,40,72]</pre> |
||
Line 3,763: | Line 3,763: | ||
=={{header|Mathematica}}/{{header|Wolfram Language}}== |
=={{header|Mathematica}}/{{header|Wolfram Language}}== |
||
===Using pattern matching=== |
===Using pattern matching=== |
||
< |
<syntaxhighlight lang="mathematica">bubbleSort[{w___, x_, y_, z___}] /; x > y := bubbleSort[{w, y, x, z}] |
||
bubbleSort[sortedList_] := sortedList |
bubbleSort[sortedList_] := sortedList |
||
bubbleSort[{10, 3, 7, 1, 4, 3, 8, 13, 9}]</ |
bubbleSort[{10, 3, 7, 1, 4, 3, 8, 13, 9}]</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>{1, 3, 3, 4, 7, 8, 9, 10, 13}</pre> |
<pre>{1, 3, 3, 4, 7, 8, 9, 10, 13}</pre> |
||
===Classic version=== |
===Classic version=== |
||
< |
<syntaxhighlight lang="mathematica">ClearAll[BubbleSort] |
||
BubbleSort[in_List] := Module[{x = in, l = Length[in], swapped}, |
BubbleSort[in_List] := Module[{x = in, l = Length[in], swapped}, |
||
swapped = True; |
swapped = True; |
||
Line 3,785: | Line 3,785: | ||
x |
x |
||
] |
] |
||
BubbleSort[{1, 12, 3, 7, 2, 8, 4, 7, 6}]</ |
BubbleSort[{1, 12, 3, 7, 2, 8, 4, 7, 6}]</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>{1, 2, 3, 4, 6, 7, 7, 8, 12}</pre> |
<pre>{1, 2, 3, 4, 6, 7, 7, 8, 12}</pre> |
||
Line 3,791: | Line 3,791: | ||
=={{header|MATLAB}}== |
=={{header|MATLAB}}== |
||
< |
<syntaxhighlight lang="matlab">function list = bubbleSort(list) |
||
hasChanged = true; |
hasChanged = true; |
||
Line 3,810: | Line 3,810: | ||
end %for |
end %for |
||
end %while |
end %while |
||
end %bubbleSort</ |
end %bubbleSort</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 3,820: | Line 3,820: | ||
=={{header|MAXScript}}== |
=={{header|MAXScript}}== |
||
< |
<syntaxhighlight lang="maxscript">fn bubbleSort arr = |
||
( |
( |
||
while true do |
while true do |
||
Line 3,836: | Line 3,836: | ||
) |
) |
||
arr |
arr |
||
)</ |
)</syntaxhighlight> |
||
-- Usage |
-- Usage |
||
< |
<syntaxhighlight lang="maxscript">myArr = #(9, 8, 7, 6, 5, 4, 3, 2, 1) |
||
myArr = bubbleSort myArr</ |
myArr = bubbleSort myArr</syntaxhighlight> |
||
=={{header|MMIX}}== |
=={{header|MMIX}}== |
||
< |
<syntaxhighlight lang="mmix">Ja IS $127 |
||
LOC Data_Segment |
LOC Data_Segment |
||
Line 3,921: | Line 3,921: | ||
JMP 2B % loop |
JMP 2B % loop |
||
1H XOR $255,$255,$255 |
1H XOR $255,$255,$255 |
||
TRAP 0,Halt,0 % exit(0)</ |
TRAP 0,Halt,0 % exit(0)</syntaxhighlight> |
||
=={{header|Modula-2}}== |
=={{header|Modula-2}}== |
||
< |
<syntaxhighlight lang="modula2">PROCEDURE BubbleSort(VAR a: ARRAY OF INTEGER); |
||
VAR |
VAR |
||
changed: BOOLEAN; |
changed: BOOLEAN; |
||
Line 3,942: | Line 3,942: | ||
END |
END |
||
UNTIL NOT changed |
UNTIL NOT changed |
||
END BubbleSort;</ |
END BubbleSort;</syntaxhighlight> |
||
=={{header|Modula-3}}== |
=={{header|Modula-3}}== |
||
< |
<syntaxhighlight lang="modula3">MODULE Bubble; |
||
PROCEDURE Sort(VAR a: ARRAY OF INTEGER) = |
PROCEDURE Sort(VAR a: ARRAY OF INTEGER) = |
||
Line 3,965: | Line 3,965: | ||
END; |
END; |
||
END Sort; |
END Sort; |
||
END Bubble.</ |
END Bubble.</syntaxhighlight> |
||
=={{header|N/t/roff}}== |
=={{header|N/t/roff}}== |
||
Line 3,977: | Line 3,977: | ||
{{works with|GROFF (GNU Troff)|1.22.2}} |
{{works with|GROFF (GNU Troff)|1.22.2}} |
||
< |
<syntaxhighlight lang="n/t/roff"> |
||
.ig |
.ig |
||
Bubble sort algorithm in Troff |
Bubble sort algorithm in Troff |
||
Line 4,048: | Line 4,048: | ||
.nr Ai 0 1 |
.nr Ai 0 1 |
||
.while \n(Ai<\n(Ac \n[A\n+[Ai]] |
.while \n(Ai<\n(Ac \n[A\n+[Ai]] |
||
</syntaxhighlight> |
|||
</lang> |
|||
===Output=== |
===Output=== |
||
Line 4,057: | Line 4,057: | ||
=={{header|Nanoquery}}== |
=={{header|Nanoquery}}== |
||
{{trans|Python}} |
{{trans|Python}} |
||
< |
<syntaxhighlight lang="nanoquery">def bubble_sort(seq) |
||
changed = true |
changed = true |
||
Line 4,084: | Line 4,084: | ||
testset = bubble_sort(testset) |
testset = bubble_sort(testset) |
||
println testset |
println testset |
||
end</ |
end</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 4,093: | Line 4,093: | ||
=={{header|Nemerle}}== |
=={{header|Nemerle}}== |
||
===Functional=== |
===Functional=== |
||
< |
<syntaxhighlight lang="nemerle">using System; |
||
using System.Console; |
using System.Console; |
||
Line 4,135: | Line 4,135: | ||
WriteLine(Bubblesort(several)); |
WriteLine(Bubblesort(several)); |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
===Imperative=== |
===Imperative=== |
||
{{trans|C#}} |
{{trans|C#}} |
||
We use an array for this version so that we can update in place. We could use a C# style list (as in the C# example), but that seemed too easy to confuse with a Nemerle style list. |
We use an array for this version so that we can update in place. We could use a C# style list (as in the C# example), but that seemed too easy to confuse with a Nemerle style list. |
||
< |
<syntaxhighlight lang="nemerle">using System; |
||
using System.Console; |
using System.Console; |
||
Line 4,171: | Line 4,171: | ||
Write($"$i "); |
Write($"$i "); |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|NetRexx}}== |
=={{header|NetRexx}}== |
||
< |
<syntaxhighlight lang="netrexx">/* NetRexx */ |
||
options replace format comments java crossref savelog symbols binary |
options replace format comments java crossref savelog symbols binary |
||
Line 4,210: | Line 4,210: | ||
return list |
return list |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre style="height: 20ex; overflow: scroll;"> |
<pre style="height: 20ex; overflow: scroll;"> |
||
Line 4,235: | Line 4,235: | ||
===Translation of Pseudocode=== |
===Translation of Pseudocode=== |
||
This version is a direct implementation of this task's pseudocode. |
This version is a direct implementation of this task's pseudocode. |
||
< |
<syntaxhighlight lang="netrexx">/* NetRexx */ |
||
options replace format comments java crossref savelog symbols binary |
options replace format comments java crossref savelog symbols binary |
||
Line 4,281: | Line 4,281: | ||
method isFalse public constant binary returns boolean |
method isFalse public constant binary returns boolean |
||
return \isTrue |
return \isTrue |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Nim}}== |
=={{header|Nim}}== |
||
< |
<syntaxhighlight lang="nim">proc bubbleSort[T](a: var openarray[T]) = |
||
var t = true |
var t = true |
||
for n in countdown(a.len-2, 0): |
for n in countdown(a.len-2, 0): |
||
Line 4,296: | Line 4,296: | ||
var a = @[4, 65, 2, -31, 0, 99, 2, 83, 782] |
var a = @[4, 65, 2, -31, 0, 99, 2, 83, 782] |
||
bubbleSort a |
bubbleSort a |
||
echo a</ |
echo a</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>@[-31, 0, 2, 2, 4, 65, 83, 99, 782]</pre> |
<pre>@[-31, 0, 2, 2, 4, 65, 83, 99, 782]</pre> |
||
Line 4,302: | Line 4,302: | ||
=={{header|Objeck}}== |
=={{header|Objeck}}== |
||
{{trans|C}} |
{{trans|C}} |
||
< |
<syntaxhighlight lang="objeck"> |
||
function : Swap(p : Int[]) ~ Nil { |
function : Swap(p : Int[]) ~ Nil { |
||
t := p[0]; |
t := p[0]; |
||
Line 4,322: | Line 4,322: | ||
while (sorted = false); |
while (sorted = false); |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Objective-C}}== |
=={{header|Objective-C}}== |
||
< |
<syntaxhighlight lang="objc">- (NSArray *) bubbleSort:(NSMutableArray *)unsorted { |
||
BOOL done = false; |
BOOL done = false; |
||
Line 4,340: | Line 4,340: | ||
return unsorted; |
return unsorted; |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|OCaml}}== |
=={{header|OCaml}}== |
||
Line 4,346: | Line 4,346: | ||
This version checks for changes in a separate step for simplicity. |
This version checks for changes in a separate step for simplicity. |
||
< |
<syntaxhighlight lang="ocaml">let rec bsort s = |
||
let rec _bsort = function |
let rec _bsort = function |
||
| x :: x2 :: xs when x > x2 -> |
| x :: x2 :: xs when x > x2 -> |
||
Line 4,356: | Line 4,356: | ||
let t = _bsort s in |
let t = _bsort s in |
||
if t = s then t |
if t = s then t |
||
else bsort t</ |
else bsort t</syntaxhighlight> |
||
This version uses the polymorphic <tt>option</tt> type to designate unchanged lists. (The type signature of <tt>_bsort</tt> is now <tt>'a list -> 'a list option</tt>.) It is slightly faster than the previous one. |
This version uses the polymorphic <tt>option</tt> type to designate unchanged lists. (The type signature of <tt>_bsort</tt> is now <tt>'a list -> 'a list option</tt>.) It is slightly faster than the previous one. |
||
< |
<syntaxhighlight lang="ocaml">let rec bsort s = |
||
let rec _bsort = function |
let rec _bsort = function |
||
| x :: x2 :: xs when x > x2 -> begin |
| x :: x2 :: xs when x > x2 -> begin |
||
Line 4,375: | Line 4,375: | ||
match _bsort s with |
match _bsort s with |
||
| None -> s |
| None -> s |
||
| Some s2 -> bsort s2</ |
| Some s2 -> bsort s2</syntaxhighlight> |
||
=={{header|Octave}}== |
=={{header|Octave}}== |
||
< |
<syntaxhighlight lang="octave">function s = bubblesort(v) |
||
itemCount = length(v); |
itemCount = length(v); |
||
do |
do |
||
Line 4,391: | Line 4,391: | ||
until(hasChanged == false) |
until(hasChanged == false) |
||
s = v; |
s = v; |
||
endfunction</ |
endfunction</syntaxhighlight> |
||
< |
<syntaxhighlight lang="octave">v = [9,8,7,3,1,100]; |
||
disp(bubblesort(v));</ |
disp(bubblesort(v));</syntaxhighlight> |
||
=={{header|Ol}}== |
=={{header|Ol}}== |
||
< |
<syntaxhighlight lang="scheme"> |
||
(define (bubble-sort x ??) |
(define (bubble-sort x ??) |
||
(define (sort-step l) |
(define (sort-step l) |
||
Line 4,416: | Line 4,416: | ||
(print |
(print |
||
(bubble-sort (iota 100) <)) |
(bubble-sort (iota 100) <)) |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{Out}} |
{{Out}} |
||
Line 4,429: | Line 4,429: | ||
{{trans|NetRexx}} |
{{trans|NetRexx}} |
||
This version exploits the "Collection Classes" and some other features of the language that are only available in Open Object Rexx. |
This version exploits the "Collection Classes" and some other features of the language that are only available in Open Object Rexx. |
||
< |
<syntaxhighlight lang="oorexx">/* Rexx */ |
||
Do |
Do |
||
placesList = sampleData() |
placesList = sampleData() |
||
Line 4,491: | Line 4,491: | ||
Exit |
Exit |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre style="height: 20ex; overflow: scroll;"> |
<pre style="height: 20ex; overflow: scroll;"> |
||
Line 4,515: | Line 4,515: | ||
===Translation of Pseudocode=== |
===Translation of Pseudocode=== |
||
This version is a direct implementation of this task's pseudocode. |
This version is a direct implementation of this task's pseudocode. |
||
< |
<syntaxhighlight lang="oorexx">/* Rexx */ |
||
Do |
Do |
||
placesList = sampleData() |
placesList = sampleData() |
||
Line 4,587: | Line 4,587: | ||
isFalse: procedure |
isFalse: procedure |
||
return \isTrue() |
return \isTrue() |
||
</syntaxhighlight> |
|||
</lang> |
|||
===Classic [[REXX|Rexx]] Implementation=== |
===Classic [[REXX|Rexx]] Implementation=== |
||
A more "traditional" implementation of version 1 using only Rexx primitive constructs. This version has been tested with the ''Open Object Rexx'' and ''Regina'' Rexx interpreters and could equally have been exhibited as a [[#REXX|Rexx]] solution. |
A more "traditional" 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. |
||
< |
<syntaxhighlight lang="oorexx">/* Rexx */ |
||
Do |
Do |
||
placesList. = '' |
placesList. = '' |
||
Line 4,652: | Line 4,652: | ||
End |
End |
||
Exit |
Exit |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Oz}}== |
=={{header|Oz}}== |
||
In-place sorting of mutable arrays: |
In-place sorting of mutable arrays: |
||
< |
<syntaxhighlight lang="oz">declare |
||
proc {BubbleSort Arr} |
proc {BubbleSort Arr} |
||
proc {Swap I J} |
proc {Swap I J} |
||
Line 4,678: | Line 4,678: | ||
in |
in |
||
{BubbleSort Arr} |
{BubbleSort Arr} |
||
{Inspect Arr}</ |
{Inspect Arr}</syntaxhighlight> |
||
Purely-functional sorting of immutable lists: |
Purely-functional sorting of immutable lists: |
||
< |
<syntaxhighlight lang="oz">declare |
||
local |
local |
||
fun {Loop Xs Changed ?IsSorted} |
fun {Loop Xs Changed ?IsSorted} |
||
Line 4,705: | Line 4,705: | ||
end |
end |
||
in |
in |
||
{Show {BubbleSort [3 1 4 1 5 9 2 6 5]}}</ |
{Show {BubbleSort [3 1 4 1 5 9 2 6 5]}}</syntaxhighlight> |
||
=={{header|PARI/GP}}== |
=={{header|PARI/GP}}== |
||
< |
<syntaxhighlight lang="parigp">bubbleSort(v)={ |
||
for(i=1,#v-1, |
for(i=1,#v-1, |
||
for(j=i+1,#v, |
for(j=i+1,#v, |
||
Line 4,719: | Line 4,719: | ||
); |
); |
||
v |
v |
||
};</ |
};</syntaxhighlight> |
||
=={{header|Pascal}}== |
=={{header|Pascal}}== |
||
< |
<syntaxhighlight lang="pascal">procedure bubble_sort(var list: array of real); |
||
var |
var |
||
i, j, n: integer; |
i, j, n: integer; |
||
Line 4,736: | Line 4,736: | ||
list[j + 1] := t; |
list[j + 1] := t; |
||
end; |
end; |
||
end;</ |
end;</syntaxhighlight> |
||
Usage:< |
Usage:<syntaxhighlight lang="pascal">var |
||
list: array[0 .. 9] of real; |
list: array[0 .. 9] of real; |
||
// ... |
// ... |
||
bubble_sort(list);</ |
bubble_sort(list);</syntaxhighlight> |
||
=={{header|Perl}}== |
=={{header|Perl}}== |
||
< |
<syntaxhighlight lang="perl"># Sorts an array in place |
||
sub bubble_sort { |
sub bubble_sort { |
||
for my $i (0 .. $#_){ |
for my $i (0 .. $#_){ |
||
Line 4,751: | Line 4,751: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
Usage: |
Usage: |
||
< |
<syntaxhighlight lang="perl">my @a = (39, 25, 30, 28, 36, 72, 98, 25, 43, 38); |
||
bubble_sort(@a);</ |
bubble_sort(@a);</syntaxhighlight> |
||
=={{header|Phix}}== |
=={{header|Phix}}== |
||
<!--< |
<!--<syntaxhighlight lang="phix">(phixonline)--> |
||
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span> |
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span> |
||
Line 4,786: | Line 4,786: | ||
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"After: "</span><span style="color: #0000FF;">)</span> |
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"After: "</span><span style="color: #0000FF;">)</span> |
||
<span style="color: #0000FF;">?</span><span style="color: #000000;">bubble_sort</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span> |
<span style="color: #0000FF;">?</span><span style="color: #000000;">bubble_sort</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span> |
||
<!--</ |
<!--</syntaxhighlight>--> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 4,795: | Line 4,795: | ||
=={{header|PHP}}== |
=={{header|PHP}}== |
||
< |
<syntaxhighlight lang="php">function bubbleSort(array $array){ |
||
foreach($array as $i => &$val){ |
foreach($array as $i => &$val){ |
||
foreach($array as $k => &$val2){ |
foreach($array as $k => &$val2){ |
||
Line 4,807: | Line 4,807: | ||
} |
} |
||
return $array; |
return $array; |
||
}</ |
}</syntaxhighlight> |
||
=={{header|PicoLisp}}== |
=={{header|PicoLisp}}== |
||
< |
<syntaxhighlight lang="picolisp">(de bubbleSort (Lst) |
||
(use Chg |
(use Chg |
||
(loop |
(loop |
||
Line 4,818: | Line 4,818: | ||
(xchg L (cdr L)) |
(xchg L (cdr L)) |
||
(on Chg) ) ) |
(on Chg) ) ) |
||
(NIL Chg Lst) ) ) )</ |
(NIL Chg Lst) ) ) )</syntaxhighlight> |
||
=={{header|PL/I}}== |
=={{header|PL/I}}== |
||
< |
<syntaxhighlight lang="pli">/* A primitive bubble sort */ |
||
bubble_sort: procedure (A); |
bubble_sort: procedure (A); |
||
declare A(*) fixed binary; |
declare A(*) fixed binary; |
||
Line 4,836: | Line 4,836: | ||
end; |
end; |
||
end; |
end; |
||
end bubble_sort;</ |
end bubble_sort;</syntaxhighlight> |
||
=={{header|Pop11}}== |
=={{header|Pop11}}== |
||
< |
<syntaxhighlight lang="pop11">define bubble_sort(v); |
||
lvars n=length(v), done=false, i; |
lvars n=length(v), done=false, i; |
||
while not(done) do |
while not(done) do |
||
Line 4,857: | Line 4,857: | ||
vars ar = { 10 8 6 4 2 1 3 5 7 9}; |
vars ar = { 10 8 6 4 2 1 3 5 7 9}; |
||
bubble_sort(ar); |
bubble_sort(ar); |
||
ar =></ |
ar =></syntaxhighlight> |
||
=={{header|PostScript}}== |
=={{header|PostScript}}== |
||
<syntaxhighlight lang="postscript"> |
|||
<lang PostScript> |
|||
/bubblesort{ |
/bubblesort{ |
||
/x exch def |
/x exch def |
||
Line 4,882: | Line 4,882: | ||
x pstack |
x pstack |
||
}def |
}def |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|PowerShell}}== |
=={{header|PowerShell}}== |
||
< |
<syntaxhighlight lang="powershell">function bubblesort ($a) { |
||
$l = $a.Length |
$l = $a.Length |
||
$hasChanged = $true |
$hasChanged = $true |
||
Line 4,898: | Line 4,898: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Prolog}}== |
=={{header|Prolog}}== |
||
Line 4,904: | Line 4,904: | ||
to the bubble sort algorithm. Some of these are easier and shorter to code and work as well if not better. Having said that, |
to the bubble sort algorithm. Some of these are easier and shorter to code and work as well if not better. Having said that, |
||
it's difficult to think of a reason to code the bubble sort these days except as an example of inefficiency. |
it's difficult to think of a reason to code the bubble sort these days except as an example of inefficiency. |
||
< |
<syntaxhighlight lang="prolog">%___________________________________________________________________________ |
||
% Bubble sort |
% Bubble sort |
||
Line 4,923: | Line 4,923: | ||
writef(' input=%w\n', [In]), |
writef(' input=%w\n', [In]), |
||
bubblesort(In, R), |
bubblesort(In, R), |
||
writef('-> %w\n', [R]).</ |
writef('-> %w\n', [R]).</syntaxhighlight> |
||
for example: |
for example: |
||
<pre>?- test. |
<pre>?- test. |
||
Line 4,936: | Line 4,936: | ||
Should be ISO (but tested only with GNU Prolog). |
Should be ISO (but tested only with GNU Prolog). |
||
Note: doesn't constuct list for each swap, only for each pass. |
Note: doesn't constuct list for each swap, only for each pass. |
||
< |
<syntaxhighlight lang="prolog">:- initialization(main). |
||
Line 4,957: | Line 4,957: | ||
test([8,9,1,3,4,2,6,5,4]). |
test([8,9,1,3,4,2,6,5,4]). |
||
main :- test(T), bubble_sort(T,_), halt.</ |
main :- test(T), bubble_sort(T,_), halt.</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
<pre>[8,9,1,3,4,2,6,5,4] |
<pre>[8,9,1,3,4,2,6,5,4] |
||
Line 4,966: | Line 4,966: | ||
=={{header|PureBasic}}== |
=={{header|PureBasic}}== |
||
< |
<syntaxhighlight lang="purebasic">Procedure bubbleSort(Array a(1)) |
||
Protected i, itemCount, hasChanged |
Protected i, itemCount, hasChanged |
||
Line 4,980: | Line 4,980: | ||
Next |
Next |
||
Until hasChanged = #False |
Until hasChanged = #False |
||
EndProcedure</ |
EndProcedure</syntaxhighlight> |
||
=={{header|Python}}== |
=={{header|Python}}== |
||
< |
<syntaxhighlight lang="python">def bubble_sort(seq): |
||
"""Inefficiently sort the mutable sequence (list) in place. |
"""Inefficiently sort the mutable sequence (list) in place. |
||
seq MUST BE A MUTABLE SEQUENCE. |
seq MUST BE A MUTABLE SEQUENCE. |
||
Line 5,008: | Line 5,008: | ||
assert testcase != testset # we've shuffled it |
assert testcase != testset # we've shuffled it |
||
bubble_sort(testcase) |
bubble_sort(testcase) |
||
assert testcase == testset # we've unshuffled it back into a copy</ |
assert testcase == testset # we've unshuffled it back into a copy</syntaxhighlight> |
||
=={{header|Quackery}}== |
=={{header|Quackery}}== |
||
< |
<syntaxhighlight lang="quackery"> [ stack ] is sorted ( --> s ) |
||
[ rot tuck over peek |
[ rot tuck over peek |
||
Line 5,034: | Line 5,034: | ||
[ 10 random join ] |
[ 10 random join ] |
||
say "Before: " dup echo cr |
say "Before: " dup echo cr |
||
say "After: " bubble echo</ |
say "After: " bubble echo</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 5,043: | Line 5,043: | ||
=={{header|Qi}}== |
=={{header|Qi}}== |
||
< |
<syntaxhighlight lang="qi">(define bubble-shot |
||
[A] -> [A] |
[A] -> [A] |
||
[A B|R] -> [B|(bubble-shot [A|R])] where (> A B) |
[A B|R] -> [B|(bubble-shot [A|R])] where (> A B) |
||
Line 5,052: | Line 5,052: | ||
(bubble-sort [6 8 5 9 3 2 2 1 4 7]) |
(bubble-sort [6 8 5 9 3 2 2 1 4 7]) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|R}}== |
=={{header|R}}== |
||
The previously solution missed out on a cool R trick for swapping items and had no check for lists of length 1. As R is 1-indexed, we have aimed to be as faithful as we can to the given pseudo-code. |
The previously solution missed out on a cool R trick for swapping items and had no check for lists of length 1. As R is 1-indexed, we have aimed to be as faithful as we can to the given pseudo-code. |
||
< |
<syntaxhighlight lang="rsplus">bubbleSort <- function(items) |
||
{ |
{ |
||
repeat |
repeat |
||
Line 5,078: | Line 5,078: | ||
ints <- c(1, 10, 2, 5, -1, 5, -19, 4, 23, 0) |
ints <- c(1, 10, 2, 5, -1, 5, -19, 4, 23, 0) |
||
numerics <- c(1, -3.2, 5.2, 10.8, -5.7, 7.3, 3.5, 0, -4.1, -9.5) |
numerics <- c(1, -3.2, 5.2, 10.8, -5.7, 7.3, 3.5, 0, -4.1, -9.5) |
||
strings <- c("We", "hold", "these", "truths", "to", "be", "self-evident", "that", "all", "men", "are", "created", "equal")</ |
strings <- c("We", "hold", "these", "truths", "to", "be", "self-evident", "that", "all", "men", "are", "created", "equal")</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 5,090: | Line 5,090: | ||
=={{header|Ra}}== |
=={{header|Ra}}== |
||
<syntaxhighlight lang="ra"> |
|||
<lang Ra> |
|||
class BubbleSort |
class BubbleSort |
||
**Sort a list with the Bubble Sort algorithm** |
**Sort a list with the Bubble Sort algorithm** |
||
Line 5,122: | Line 5,122: | ||
list[i + 1] := temp |
list[i + 1] := temp |
||
changed := true |
changed := true |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Racket}}== |
=={{header|Racket}}== |
||
Line 5,128: | Line 5,128: | ||
This bubble sort sorts the elelement in the vector v with regard to <?. |
This bubble sort sorts the elelement in the vector v with regard to <?. |
||
< |
<syntaxhighlight lang="racket"> |
||
#lang racket |
#lang racket |
||
Line 5,145: | Line 5,145: | ||
(when again? (loop (- max 1) #f))) |
(when again? (loop (- max 1) #f))) |
||
v) |
v) |
||
</syntaxhighlight> |
|||
</lang> |
|||
Example: Sorting a vector of length 10 with random entries. |
Example: Sorting a vector of length 10 with random entries. |
||
< |
<syntaxhighlight lang="racket"> |
||
(bubble-sort < (for/vector ([_ 10]) (random 20))) |
(bubble-sort < (for/vector ([_ 10]) (random 20))) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Raku}}== |
=={{header|Raku}}== |
||
Line 5,156: | Line 5,156: | ||
{{works with|Rakudo|#24 "Seoul"}} |
{{works with|Rakudo|#24 "Seoul"}} |
||
<lang |
<syntaxhighlight lang="raku" line>sub bubble_sort (@a) { |
||
for ^@a -> $i { |
for ^@a -> $i { |
||
for $i ^..^ @a -> $j { |
for $i ^..^ @a -> $j { |
||
Line 5,162: | Line 5,162: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|REALbasic}}== |
=={{header|REALbasic}}== |
||
Line 5,168: | Line 5,168: | ||
Sorts an array of Integers |
Sorts an array of Integers |
||
<syntaxhighlight lang="vb"> |
|||
<lang vb> |
|||
Dim sortable() As Integer = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) |
Dim sortable() As Integer = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) |
||
sortable.Shuffle() ' sortable is now randomized |
sortable.Shuffle() ' sortable is now randomized |
||
Line 5,188: | Line 5,188: | ||
Loop Until Not swapped |
Loop Until Not swapped |
||
'sortable is now sorted |
'sortable is now sorted |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|REXX}}== |
=={{header|REXX}}== |
||
===version 0, alpha-numeric vertical list=== |
===version 0, alpha-numeric vertical list=== |
||
This REXX version sorts (using a bubble sort) and displays an array (of alpha-numeric items) in a vertical list. |
This REXX version sorts (using a bubble sort) and displays an array (of alpha-numeric items) in a vertical list. |
||
< |
<syntaxhighlight lang="rexx">/*REXX program sorts an array (of any kind of items) using the bubble─sort algorithm.*/ |
||
call gen /*generate the array elements (items).*/ |
call gen /*generate the array elements (items).*/ |
||
call show 'before sort' /*show the before array elements. */ |
call show 'before sort' /*show the before array elements. */ |
||
Line 5,223: | Line 5,223: | ||
return |
return |
||
/*──────────────────────────────────────────────────────────────────────────────────────*/ |
/*──────────────────────────────────────────────────────────────────────────────────────*/ |
||
show: do j=1 for #; say ' element' right(j,length(#)) arg(1)":" @.j; end; return</ |
show: do j=1 for #; say ' element' right(j,length(#)) arg(1)":" @.j; end; return</syntaxhighlight> |
||
{{out|output|text= when using the internal array list:}} |
{{out|output|text= when using the internal array list:}} |
||
<br>(Shown at '''<sup>5</sup>/<sub>6</sub>''' size.) |
<br>(Shown at '''<sup>5</sup>/<sub>6</sub>''' size.) |
||
Line 5,282: | Line 5,282: | ||
Programming note: a check was made to not exceed REXX's upper range limit of the '''random''' BIF. |
Programming note: a check was made to not exceed REXX's upper range limit of the '''random''' BIF. |
||
< |
<syntaxhighlight lang="rexx">/*REXX program sorts an array (of any kind of numbers) using the bubble─sort algorithm.*/ |
||
parse arg N .; if N=='' | N=="," then N=30 /*obtain optional size of array from CL*/ |
parse arg N .; if N=='' | N=="," then N=30 /*obtain optional size of array from CL*/ |
||
call gen N /*generate the array elements (items). */ |
call gen N /*generate the array elements (items). */ |
||
Line 5,297: | Line 5,297: | ||
/*──────────────────────────────────────────────────────────────────────────────────────*/ |
/*──────────────────────────────────────────────────────────────────────────────────────*/ |
||
gen: h=min(N+N,1e5); w=length(h); do j=1 for N; @.j=random(h); end; return |
gen: h=min(N+N,1e5); w=length(h); do j=1 for N; @.j=random(h); end; return |
||
show: parse arg $; do k=1 for N; $=$ right(@.k, w); end; say $; return</ |
show: parse arg $; do k=1 for N; $=$ right(@.k, w); end; say $; return</syntaxhighlight> |
||
{{out|output|text= when using a internally generated random array of thirty integers (which are right-justified for alignment in the display):}} |
{{out|output|text= when using a internally generated random array of thirty integers (which are right-justified for alignment in the display):}} |
||
<pre> |
<pre> |
||
Line 5,306: | Line 5,306: | ||
===version 2, random integers, horizontal list=== |
===version 2, random integers, horizontal list=== |
||
{{trans|PL/I}} |
{{trans|PL/I}} |
||
< |
<syntaxhighlight lang="rexx"> |
||
/*REXX*/ |
/*REXX*/ |
||
Call random ,,1000 |
Call random ,,1000 |
||
Line 5,331: | Line 5,331: | ||
show: |
show: |
||
l=''; Do i=1 To a.0; l=l a.i; End; Say arg(1)':'l |
l=''; Do i=1 To a.0; l=l a.i; End; Say arg(1)':'l |
||
Return</ |
Return</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>vorher : 9 17 16 19 5 7 3 20 16 0 |
<pre>vorher : 9 17 16 19 5 7 3 20 16 0 |
||
Line 5,347: | Line 5,347: | ||
Also note that only four snapshots of the sort-in-progress is shown here, the REXX program will show a snapshot of ''every'' |
Also note that only four snapshots of the sort-in-progress is shown here, the REXX program will show a snapshot of ''every'' |
||
<br>sorting pass; the ''at (about) nnn% sorted'' was added after-the-fact. |
<br>sorting pass; the ''at (about) nnn% sorted'' was added after-the-fact. |
||
< |
<syntaxhighlight lang="rexx">/*REXX program sorts an array (of any kind of numbers) using the bubble─sort algorithm.*/ |
||
parse arg N seed . /*obtain optional size of array from CL*/ |
parse arg N seed . /*obtain optional size of array from CL*/ |
||
if N=='' | N=="," then N=30 /*Not specified? Then use the default.*/ |
if N=='' | N=="," then N=30 /*Not specified? Then use the default.*/ |
||
Line 5,378: | Line 5,378: | ||
do s=# for # by -1; say $.s; end /*s*/ |
do s=# for # by -1; say $.s; end /*s*/ |
||
say "└"copies('─', #) /*display the horizontal axis at bottom*/ |
say "└"copies('─', #) /*display the horizontal axis at bottom*/ |
||
return</ |
return</syntaxhighlight> |
||
{{out|output|text= when using the default input:}} |
{{out|output|text= when using the default input:}} |
||
<pre> |
<pre> |
||
Line 5,512: | Line 5,512: | ||
=={{header|Ring}}== |
=={{header|Ring}}== |
||
< |
<syntaxhighlight lang="ring">bubbleList = [4,2,1,3] |
||
flag = 0 |
flag = 0 |
||
bubbleSort(bubbleList) |
bubbleSort(bubbleList) |
||
Line 5,530: | Line 5,530: | ||
next |
next |
||
end |
end |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Ruby}}== |
=={{header|Ruby}}== |
||
{{eff note|Ruby|Array.sort!}}This example adds the bubblesort! method to the Array object. Below are two different methods that show four different iterating constructs in ruby. |
{{eff note|Ruby|Array.sort!}}This example adds the bubblesort! method to the Array object. Below are two different methods that show four different iterating constructs in ruby. |
||
< |
<syntaxhighlight lang="ruby">class Array |
||
def bubblesort1! |
def bubblesort1! |
||
length.times do |j| |
length.times do |j| |
||
Line 5,558: | Line 5,558: | ||
ary.bubblesort1! |
ary.bubblesort1! |
||
p ary |
p ary |
||
# => [3, 4, 6, 6, 8, 23, 78]</ |
# => [3, 4, 6, 6, 8, 23, 78]</syntaxhighlight> |
||
=={{header|Run BASIC}}== |
=={{header|Run BASIC}}== |
||
< |
<syntaxhighlight lang="runbasic">siz = 100 |
||
dim data$(siz) |
dim data$(siz) |
||
unSorted = 1 |
unSorted = 1 |
||
Line 5,575: | Line 5,575: | ||
END IF |
END IF |
||
NEXT |
NEXT |
||
WEND</ |
WEND</syntaxhighlight> |
||
=={{header|Rust}}== |
=={{header|Rust}}== |
||
< |
<syntaxhighlight lang="rust">fn bubble_sort<T: Ord>(values: &mut[T]) { |
||
let mut n = values.len(); |
let mut n = values.len(); |
||
let mut swapped = true; |
let mut swapped = true; |
||
Line 5,610: | Line 5,610: | ||
bubble_sort(&mut strings); |
bubble_sort(&mut strings); |
||
println!("After: {:?}", strings); |
println!("After: {:?}", strings); |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Sather}}== |
=={{header|Sather}}== |
||
< |
<syntaxhighlight lang="sather">class SORT{T < $IS_LT{T}} is |
||
private swap(inout a, inout b:T) is |
private swap(inout a, inout b:T) is |
||
temp ::= a; |
temp ::= a; |
||
Line 5,633: | Line 5,633: | ||
end; |
end; |
||
end; |
end; |
||
end;</ |
end;</syntaxhighlight> |
||
< |
<syntaxhighlight lang="sather">class MAIN is |
||
main is |
main is |
||
a:ARRAY{INT} := |10, 9, 8, 7, 6, -10, 5, 4|; |
a:ARRAY{INT} := |10, 9, 8, 7, 6, -10, 5, 4|; |
||
Line 5,641: | Line 5,641: | ||
#OUT + a + "\n"; |
#OUT + a + "\n"; |
||
end; |
end; |
||
end;</ |
end;</syntaxhighlight> |
||
This should be able to sort (in ascending order) any object for which <code>is_lt</code> (less than) is defined. |
This should be able to sort (in ascending order) any object for which <code>is_lt</code> (less than) is defined. |
||
Line 5,649: | Line 5,649: | ||
This slightly more complex version of Bubble Sort avoids errors with indices. |
This slightly more complex version of Bubble Sort avoids errors with indices. |
||
< |
<syntaxhighlight lang="scala">def bubbleSort[T](arr: Array[T])(implicit o: Ordering[T]) { |
||
import o._ |
import o._ |
||
val consecutiveIndices = (arr.indices, arr.indices drop 1).zipped |
val consecutiveIndices = (arr.indices, arr.indices drop 1).zipped |
||
Line 5,664: | Line 5,664: | ||
} |
} |
||
} while(hasChanged) |
} while(hasChanged) |
||
}</ |
}</syntaxhighlight> |
||
< |
<syntaxhighlight lang="scala">import scala.annotation.tailrec |
||
def bubbleSort(xt: List[Int]) = { |
def bubbleSort(xt: List[Int]) = { |
||
Line 5,679: | Line 5,679: | ||
} |
} |
||
bubble(xt, Nil, Nil) |
bubble(xt, Nil, Nil) |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Scheme}}== |
=={{header|Scheme}}== |
||
< |
<syntaxhighlight lang="scheme">(define (bubble-sort x gt?) |
||
(letrec |
(letrec |
||
((fix (lambda (f i) |
((fix (lambda (f i) |
||
Line 5,696: | Line 5,696: | ||
(cons (car l) (sort-step (cdr l)))))))) |
(cons (car l) (sort-step (cdr l)))))))) |
||
(fix sort-step x)))</ |
(fix sort-step x)))</syntaxhighlight> |
||
This solution recursively finds the fixed point of sort-step. A comparison function must be passed to bubblesort. Example usages: |
This solution recursively finds the fixed point of sort-step. A comparison function must be passed to bubblesort. Example usages: |
||
< |
<syntaxhighlight lang="scheme">(bubble-sort (list 1 3 5 9 8 6 4 2) >) |
||
(bubble-sort (string->list "Monkey") char<?)</ |
(bubble-sort (string->list "Monkey") char<?)</syntaxhighlight> |
||
Here is the same function, using a different syntax: |
Here is the same function, using a different syntax: |
||
< |
<syntaxhighlight lang="scheme">(define (bsort l gt?) |
||
(define (dosort l) |
(define (dosort l) |
||
(cond ((null? (cdr l)) |
(cond ((null? (cdr l)) |
||
Line 5,716: | Line 5,716: | ||
l |
l |
||
(bsort try gt?)))) |
(bsort try gt?)))) |
||
</syntaxhighlight> |
|||
</lang> |
|||
For example, you could do |
For example, you could do |
||
< |
<syntaxhighlight lang="scheme">(bsort > '(2 4 6 2)) |
||
(1 2 3)</ |
(1 2 3)</syntaxhighlight> |
||
=={{header|Scilab}}== |
=={{header|Scilab}}== |
||
<lang>function b=BubbleSort(a) |
<syntaxhighlight lang="text">function b=BubbleSort(a) |
||
n=length(a) |
n=length(a) |
||
swapped=%T |
swapped=%T |
||
Line 5,737: | Line 5,737: | ||
end |
end |
||
b=a |
b=a |
||
endfunction BubbleSort</ |
endfunction BubbleSort</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre style="height:20ex">-->y=[5 4 3 2 1] |
<pre style="height:20ex">-->y=[5 4 3 2 1] |
||
Line 5,750: | Line 5,750: | ||
=={{header|Seed7}}== |
=={{header|Seed7}}== |
||
< |
<syntaxhighlight lang="seed7">const proc: bubbleSort (inout array elemType: arr) is func |
||
local |
local |
||
var boolean: swapped is FALSE; |
var boolean: swapped is FALSE; |
||
Line 5,767: | Line 5,767: | ||
end for; |
end for; |
||
until not swapped; |
until not swapped; |
||
end func;</ |
end func;</syntaxhighlight> |
||
Original source: [http://seed7.sourceforge.net/algorith/sorting.htm#bubbleSort] |
Original source: [http://seed7.sourceforge.net/algorith/sorting.htm#bubbleSort] |
||
Line 5,773: | Line 5,773: | ||
=={{header|Shen}}== |
=={{header|Shen}}== |
||
Bubble sort a vector in-place, using the < operator for comparison. |
Bubble sort a vector in-place, using the < operator for comparison. |
||
< |
<syntaxhighlight lang="shen">(tc +) |
||
(define swap |
(define swap |
||
Line 5,799: | Line 5,799: | ||
{ (vector number) --> (vector number) } |
{ (vector number) --> (vector number) } |
||
A -> (let N (limit A) |
A -> (let N (limit A) |
||
(bubble-h (one-pass A N false 2) A N)))</ |
(bubble-h (one-pass A N false 2) A N)))</syntaxhighlight> |
||
< |
<syntaxhighlight lang="shen">(datatype some-globals |
||
__________ |
__________ |
||
Line 5,812: | Line 5,812: | ||
(vector-> (value *arr*) 4 2) |
(vector-> (value *arr*) 4 2) |
||
(vector-> (value *arr*) 5 8) |
(vector-> (value *arr*) 5 8) |
||
(bubble-sort (value *arr*))</ |
(bubble-sort (value *arr*))</syntaxhighlight> |
||
Here is a more idiomatic implementation: |
Here is a more idiomatic implementation: |
||
{{trans|Qi}} |
{{trans|Qi}} |
||
< |
<syntaxhighlight lang="shen">(tc +) |
||
(define bubble-shot |
(define bubble-shot |
||
Line 5,827: | Line 5,827: | ||
(define bubble-sort |
(define bubble-sort |
||
{ (vector number) --> (vector number) } |
{ (vector number) --> (vector number) } |
||
X -> (fix (function bubble-shot) X))</ |
X -> (fix (function bubble-shot) X))</syntaxhighlight> |
||
< |
<syntaxhighlight lang="shen">(bubble-sort (@v 5 1 4 2 3 <>))</syntaxhighlight> |
||
=={{header|Sidef}}== |
=={{header|Sidef}}== |
||
< |
<syntaxhighlight lang="ruby">func bubble_sort(arr) { |
||
loop { |
loop { |
||
var swapped = false |
var swapped = false |
||
Line 5,844: | Line 5,844: | ||
} |
} |
||
return arr |
return arr |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Simula}}== |
=={{header|Simula}}== |
||
< |
<syntaxhighlight lang="simula">BEGIN |
||
PROCEDURE BUBBLESORT(A); NAME A; INTEGER ARRAY A; |
PROCEDURE BUBBLESORT(A); NAME A; INTEGER ARRAY A; |
||
Line 5,891: | Line 5,891: | ||
OUTIMAGE; |
OUTIMAGE; |
||
END;</ |
END;</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 5,900: | Line 5,900: | ||
A straight translation from the pseudocode above. Swap is done with a [[wp:Smalltalk#Code_blocks|block closure]]. |
A straight translation from the pseudocode above. Swap is done with a [[wp:Smalltalk#Code_blocks|block closure]]. |
||
< |
<syntaxhighlight lang="smalltalk">|item swap itemCount hasChanged| |
||
item := #(1 4 5 6 10 8 7 61 0 -3) copy. |
item := #(1 4 5 6 10 8 7 61 0 -3) copy. |
||
swap := |
swap := |
||
Line 5,917: | Line 5,917: | ||
[swap value: index value: index + 1. |
[swap value: index value: index + 1. |
||
hasChanged := true]]. |
hasChanged := true]]. |
||
hasChanged] whileTrue.</ |
hasChanged] whileTrue.</syntaxhighlight> |
||
=={{header|SNOBOL4}}== |
=={{header|SNOBOL4}}== |
||
< |
<syntaxhighlight lang="snobol4">* # Sort array in place, return array |
||
define('bubble(a,alen)i,j,ub,tmp') :(bubble_end) |
define('bubble(a,alen)i,j,ub,tmp') :(bubble_end) |
||
bubble i = 1; ub = alen |
bubble i = 1; ub = alen |
||
Line 5,944: | Line 5,944: | ||
sloop j = j + 1; str = str arr<j> ' ' :s(sloop) |
sloop j = j + 1; str = str arr<j> ' ' :s(sloop) |
||
output = trim(str) |
output = trim(str) |
||
end</ |
end</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 5,956: | Line 5,956: | ||
Static analysis of this code shows that it is guaranteed free of any run-time error when called from any other SPARK code. |
Static analysis of this code shows that it is guaranteed free of any run-time error when called from any other SPARK code. |
||
< |
<syntaxhighlight lang="ada">package Bubble |
||
is |
is |
||
Line 5,992: | Line 5,992: | ||
end Bubble; |
end Bubble; |
||
</syntaxhighlight> |
|||
</lang> |
|||
The next version has a postcondition to guarantee that the returned array is sorted correctly. This requires the two proof rules that follow the source. The Ada code is identical with the first version. |
The next version has a postcondition to guarantee that the returned array is sorted correctly. This requires the two proof rules that follow the source. The Ada code is identical with the first version. |
||
< |
<syntaxhighlight lang="ada">package Bubble |
||
is |
is |
||
Line 6,043: | Line 6,043: | ||
end Bubble; |
end Bubble; |
||
</syntaxhighlight> |
|||
</lang> |
|||
The proof rules are stated here without justification (but they are fairly obvious). A formal proof of these rules from the definition of Sorted has been completed. |
The proof rules are stated here without justification (but they are fairly obvious). A formal proof of these rules from the definition of Sorted has been completed. |
||
<pre> |
<pre> |
||
Line 6,058: | Line 6,058: | ||
The final version scans over a reducing portion of the array in the inner loop, consequently the proof becomes more complex. The package specification for this version is the same as the second version above. The package body defines two more proof functions. |
The final version scans over a reducing portion of the array in the inner loop, consequently the proof becomes more complex. The package specification for this version is the same as the second version above. The package body defines two more proof functions. |
||
< |
<syntaxhighlight lang="ada">package body Bubble |
||
is |
is |
||
procedure Sort (A : in out Arr) |
procedure Sort (A : in out Arr) |
||
Line 6,121: | Line 6,121: | ||
end Bubble; |
end Bubble; |
||
</syntaxhighlight> |
|||
</lang> |
|||
Completion of the proof of this version requires more rules than the previous version and they are rather more complex. Creation of these rules is quite straightforward - I tend to write whatever rules the Simplifier needs first and then validate them afterwards. A formal proof of these rules from the definition of Sorted, In_Position and Swapped has been completed. |
Completion of the proof of this version requires more rules than the previous version and they are rather more complex. Creation of these rules is quite straightforward - I tend to write whatever rules the Simplifier needs first and then validate them afterwards. A formal proof of these rules from the definition of Sorted, In_Position and Swapped has been completed. |
||
<pre>bubble_sort_rule(1): sorted(A, I, J) |
<pre>bubble_sort_rule(1): sorted(A, I, J) |
||
Line 6,195: | Line 6,195: | ||
File '''bubble.ads''': |
File '''bubble.ads''': |
||
< |
<syntaxhighlight lang="ada">package Bubble with SPARK_Mode is |
||
type Arr is array (Integer range <>) of Integer; |
type Arr is array (Integer range <>) of Integer; |
||
Line 6,217: | Line 6,217: | ||
end Bubble; |
end Bubble; |
||
</syntaxhighlight> |
|||
</lang> |
|||
File '''bubble.adb''': |
File '''bubble.adb''': |
||
< |
<syntaxhighlight lang="ada">package body Bubble with SPARK_Mode is |
||
procedure Sort (A : in out Arr) |
procedure Sort (A : in out Arr) |
||
Line 6,254: | Line 6,254: | ||
end Bubble; |
end Bubble; |
||
</syntaxhighlight> |
|||
</lang> |
|||
File '''main.adb''': |
File '''main.adb''': |
||
< |
<syntaxhighlight lang="ada">with Ada.Integer_Text_IO; |
||
with Bubble; |
with Bubble; |
||
Line 6,268: | Line 6,268: | ||
end loop; |
end loop; |
||
end Main; |
end Main; |
||
</syntaxhighlight> |
|||
</lang> |
|||
File '''bubble.gpr''': |
File '''bubble.gpr''': |
||
< |
<syntaxhighlight lang="ada">project Bubble is |
||
for Main use ("main.adb"); |
for Main use ("main.adb"); |
||
end Bubble; |
end Bubble; |
||
</syntaxhighlight> |
|||
</lang> |
|||
To verify the program, execute the command: '''gnatprove -P bubble.gpr -j0 --level=2''' |
To verify the program, execute the command: '''gnatprove -P bubble.gpr -j0 --level=2''' |
||
Line 6,322: | Line 6,322: | ||
=={{header|Stata}}== |
=={{header|Stata}}== |
||
< |
<syntaxhighlight lang="stata">mata |
||
function bubble_sort(a) { |
function bubble_sort(a) { |
||
n = length(a) |
n = length(a) |
||
Line 6,338: | Line 6,338: | ||
} |
} |
||
} |
} |
||
end</ |
end</syntaxhighlight> |
||
=={{header|Swift}}== |
=={{header|Swift}}== |
||
< |
<syntaxhighlight lang="swift">func bubbleSort<T:Comparable>(list:inout[T]) { |
||
var done = false |
var done = false |
||
while !done { |
while !done { |
||
Line 6,357: | Line 6,357: | ||
print(list1) |
print(list1) |
||
bubbleSort(list: &list1) |
bubbleSort(list: &list1) |
||
print(list1)</ |
print(list1)</syntaxhighlight> |
||
=={{header|Symsyn}}== |
=={{header|Symsyn}}== |
||
<syntaxhighlight lang="symsyn"> |
|||
<lang Symsyn> |
|||
x : 23 : 15 : 99 : 146 : 3 : 66 : 71 : 5 : 23 : 73 : 19 |
x : 23 : 15 : 99 : 146 : 3 : 66 : 71 : 5 : 23 : 73 : 19 |
||
Line 6,405: | Line 6,405: | ||
" $r $s " [] |
" $r $s " [] |
||
return |
return |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Tailspin}}== |
=={{header|Tailspin}}== |
||
< |
<syntaxhighlight lang="tailspin"> |
||
templates bubblesort |
templates bubblesort |
||
templates bubble |
templates bubble |
||
Line 6,430: | Line 6,430: | ||
[4,5,3,8,1,2,6,7,9,8,5] -> bubblesort -> !OUT::write |
[4,5,3,8,1,2,6,7,9,8,5] -> bubblesort -> !OUT::write |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Tcl}}== |
=={{header|Tcl}}== |
||
{{tcllib|struct::list}} |
{{tcllib|struct::list}} |
||
< |
<syntaxhighlight lang="tcl">package require Tcl 8.5 |
||
package require struct::list |
package require struct::list |
||
Line 6,454: | Line 6,454: | ||
} |
} |
||
puts [bubblesort {8 6 4 2 1 3 5 7 9}] ;# => 1 2 3 4 5 6 7 8 9</ |
puts [bubblesort {8 6 4 2 1 3 5 7 9}] ;# => 1 2 3 4 5 6 7 8 9</syntaxhighlight> |
||
Idiomatic code uses the builtin <code>lsort</code> instead, which is a stable O(''n'' log ''n'') sort. |
Idiomatic code uses the builtin <code>lsort</code> instead, which is a stable O(''n'' log ''n'') sort. |
||
Line 6,558: | Line 6,558: | ||
Toka does not have a bubble sort predefined, but it is easy to code a simple one: |
Toka does not have a bubble sort predefined, but it is easy to code a simple one: |
||
< |
<syntaxhighlight lang="toka">#! A simple Bubble Sort function |
||
value| array count changed | |
value| array count changed | |
||
[ ( address count -- ) |
[ ( address count -- ) |
||
Line 6,595: | Line 6,595: | ||
foo 10 .array |
foo 10 .array |
||
foo 10 bsort |
foo 10 bsort |
||
foo 10 .array</ |
foo 10 .array</syntaxhighlight> |
||
=={{header|TorqueScript}}== |
=={{header|TorqueScript}}== |
||
< |
<syntaxhighlight lang="torquescript">//Note that we're assuming that the list of numbers is separated by tabs. |
||
function bubbleSort(%list) |
function bubbleSort(%list) |
||
{ |
{ |
||
Line 6,616: | Line 6,616: | ||
} |
} |
||
return %list; |
return %list; |
||
}</ |
}</syntaxhighlight> |
||
=={{header|uBasic/4tH}}== |
=={{header|uBasic/4tH}}== |
||
<lang>PRINT "Bubble sort:" |
<syntaxhighlight lang="text">PRINT "Bubble sort:" |
||
n = FUNC (_InitArray) |
n = FUNC (_InitArray) |
||
PROC _ShowArray (n) |
PROC _ShowArray (n) |
||
Line 6,666: | Line 6,666: | ||
PRINT |
PRINT |
||
RETURN</ |
RETURN</syntaxhighlight> |
||
=={{header|Unicon}}== |
=={{header|Unicon}}== |
||
Line 6,672: | Line 6,672: | ||
=={{header|UnixPipes}}== |
=={{header|UnixPipes}}== |
||
< |
<syntaxhighlight lang="bash">rm -f _sortpass |
||
reset() { |
reset() { |
||
Line 6,694: | Line 6,694: | ||
} |
} |
||
cat to.sort | bubblesort</ |
cat to.sort | bubblesort</syntaxhighlight> |
||
=={{header|Ursala}}== |
=={{header|Ursala}}== |
||
The bubblesort function is parameterized by a relational predicate. |
The bubblesort function is parameterized by a relational predicate. |
||
< |
<syntaxhighlight lang="ursala">#import nat |
||
bubblesort "p" = @iNX ^=T ^llPrEZryPrzPlrPCXlQ/~& @l ~&aitB^?\~&a "p"?ahthPX/~&ahPfatPRC ~&ath2fahttPCPRC |
bubblesort "p" = @iNX ^=T ^llPrEZryPrzPlrPCXlQ/~& @l ~&aitB^?\~&a "p"?ahthPX/~&ahPfatPRC ~&ath2fahttPCPRC |
||
Line 6,704: | Line 6,704: | ||
#cast %nL |
#cast %nL |
||
example = bubblesort(nleq) <362,212,449,270,677,247,567,532,140,315></ |
example = bubblesort(nleq) <362,212,449,270,677,247,567,532,140,315></syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre><140,212,247,270,315,362,449,532,567,677></pre> |
<pre><140,212,247,270,315,362,449,532,567,677></pre> |
||
=={{header|Vala}}== |
=={{header|Vala}}== |
||
< |
<syntaxhighlight lang="vala">void swap(int[] array, int i1, int i2) { |
||
if (array[i1] == array[i2]) |
if (array[i1] == array[i2]) |
||
return; |
return; |
||
Line 6,737: | Line 6,737: | ||
foreach (int i in array) |
foreach (int i in array) |
||
print("%d ", i); |
print("%d ", i); |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 6,744: | Line 6,744: | ||
=={{header|VBA}}== |
=={{header|VBA}}== |
||
{{trans|Phix}}< |
{{trans|Phix}}<syntaxhighlight lang="vb">Private Function bubble_sort(s As Variant) As Variant |
||
Dim tmp As Variant |
Dim tmp As Variant |
||
Dim changed As Boolean |
Dim changed As Boolean |
||
Line 6,770: | Line 6,770: | ||
Debug.Print "After: " |
Debug.Print "After: " |
||
Debug.Print Join(bubble_sort(s), ", ") |
Debug.Print Join(bubble_sort(s), ", ") |
||
End Sub</ |
End Sub</syntaxhighlight>{{out}} |
||
<pre>Before: |
<pre>Before: |
||
4, 15, delta, 2, -31, 0, alfa, 19, gamma, 2, 13, beta, 782, 1 |
4, 15, delta, 2, -31, 0, alfa, 19, gamma, 2, 13, beta, 782, 1 |
||
Line 6,782: | Line 6,782: | ||
=====Implementation===== |
=====Implementation===== |
||
<syntaxhighlight lang="vb"> |
|||
<lang vb> |
|||
sub decr( byref n ) |
sub decr( byref n ) |
||
n = n - 1 |
n = n - 1 |
||
Line 6,814: | Line 6,814: | ||
bubbleSort = a |
bubbleSort = a |
||
end function |
end function |
||
</syntaxhighlight> |
|||
</lang> |
|||
=====Invocation===== |
=====Invocation===== |
||
<syntaxhighlight lang="vb"> |
|||
<lang vb> |
|||
dim a |
dim a |
||
a = array( "great eastern", "roe", "stirling", "albany", "leach") |
a = array( "great eastern", "roe", "stirling", "albany", "leach") |
||
Line 6,823: | Line 6,823: | ||
bubbleSort a |
bubbleSort a |
||
wscript.echo join(a,", ") |
wscript.echo join(a,", ") |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
Line 6,835: | Line 6,835: | ||
{{works with|Visual Basic .NET|9.0+}} |
{{works with|Visual Basic .NET|9.0+}} |
||
< |
<syntaxhighlight lang="vbnet">Do Until NoMoreSwaps = True |
||
NoMoreSwaps = True |
NoMoreSwaps = True |
||
For Counter = 1 To (NumberOfItems - 1) |
For Counter = 1 To (NumberOfItems - 1) |
||
Line 6,846: | Line 6,846: | ||
Next |
Next |
||
NumberOfItems = NumberOfItems - 1 |
NumberOfItems = NumberOfItems - 1 |
||
Loop</ |
Loop</syntaxhighlight> |
||
=={{header|Vlang}}== |
=={{header|Vlang}}== |
||
< |
<syntaxhighlight lang="vlang">fn bubble(mut arr []int) { |
||
println('Input: ${arr.str()}') |
println('Input: ${arr.str()}') |
||
mut count := arr.len |
mut count := arr.len |
||
Line 6,876: | Line 6,876: | ||
mut arr := [3, 5, 2, 1, 4] |
mut arr := [3, 5, 2, 1, 4] |
||
bubble(mut arr) |
bubble(mut arr) |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>Input: [3, 5, 2, 1, 4] |
<pre>Input: [3, 5, 2, 1, 4] |
||
Line 6,883: | Line 6,883: | ||
=={{header|Wren}}== |
=={{header|Wren}}== |
||
Based on the pseudo-code in the Wikipedia article. |
Based on the pseudo-code in the Wikipedia article. |
||
< |
<syntaxhighlight lang="ecmascript">var bubbleSort = Fn.new { |a| |
||
var n = a.count |
var n = a.count |
||
if (n < 2) return |
if (n < 2) return |
||
Line 6,906: | Line 6,906: | ||
System.print("After : %(a)") |
System.print("After : %(a)") |
||
System.print() |
System.print() |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 6,919: | Line 6,919: | ||
=={{header|X86 Assembly}}== |
=={{header|X86 Assembly}}== |
||
Translation of XPL0. Assemble with tasm, tlink /t |
Translation of XPL0. Assemble with tasm, tlink /t |
||
< |
<syntaxhighlight lang="asm"> .model tiny |
||
.code |
.code |
||
.486 |
.486 |
||
Line 6,948: | Line 6,948: | ||
popa |
popa |
||
ret |
ret |
||
end start</ |
end start</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 6,956: | Line 6,956: | ||
=={{header|Xojo}}== |
=={{header|Xojo}}== |
||
< |
<syntaxhighlight lang="xojo">Dim temp, count As Integer |
||
Dim isDirty As Boolean |
Dim isDirty As Boolean |
||
count = Ubound(list) // count the array size |
count = Ubound(list) // count the array size |
||
Line 6,971: | Line 6,971: | ||
End |
End |
||
Next |
Next |
||
Loop Until isDirty = False // if we made it without touching the data then we are done</ |
Loop Until isDirty = False // if we made it without touching the data then we are done</syntaxhighlight> |
||
=={{header|XPL0}}== |
=={{header|XPL0}}== |
||
< |
<syntaxhighlight lang="xpl0">include c:\cxpl\codes; \intrinsic 'code' declarations |
||
string 0; \use zero-terminated strings |
string 0; \use zero-terminated strings |
||
Line 6,997: | Line 6,997: | ||
BSort(Str, StrLen(Str)); |
BSort(Str, StrLen(Str)); |
||
Text(0, Str); CrLf(0); |
Text(0, Str); CrLf(0); |
||
]</ |
]</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 7,005: | Line 7,005: | ||
=={{header|Yabasic}}== |
=={{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) |
// Original idea by William Tang, obtained from MicroHobby 25 Years (https://microhobby.speccy.cz/zxsf/MH-25Years.pdf) |
||
Line 7,045: | Line 7,045: | ||
for x=m TO 18 : print at(18,x-1) " " : print at(18,x) t$ : pause .02 : next x |
for x=m TO 18 : print at(18,x-1) " " : print at(18,x) t$ : pause .02 : next x |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Yorick}}== |
=={{header|Yorick}}== |
||
< |
<syntaxhighlight lang="yorick">func bubblesort(&items) { |
||
itemCount = numberof(items); |
itemCount = numberof(items); |
||
do { |
do { |
||
Line 7,060: | Line 7,060: | ||
} |
} |
||
} while(hasChanged); |
} while(hasChanged); |
||
}</ |
}</syntaxhighlight> |
||
=={{header|zkl}}== |
=={{header|zkl}}== |
||
< |
<syntaxhighlight lang="zkl">fcn bubbleSort(list){ |
||
itemCount := list.len(); |
itemCount := list.len(); |
||
do{ |
do{ |
||
Line 7,075: | Line 7,075: | ||
}while(hasChanged); |
}while(hasChanged); |
||
list |
list |
||
}</ |
}</syntaxhighlight> |
||
Or, punting early termination: |
Or, punting early termination: |
||
< |
<syntaxhighlight lang="zkl">fcn bubbleSort(list){ |
||
foreach n,index in ([list.len()-1..0,-1],n){ |
foreach n,index in ([list.len()-1..0,-1],n){ |
||
if (list[index] > list[index + 1]) list.swap(index,index + 1); |
if (list[index] > list[index + 1]) list.swap(index,index + 1); |
||
} |
} |
||
list |
list |
||
}</ |
}</syntaxhighlight> |
||
< |
<syntaxhighlight lang="zkl">bubbleSort("This is a test".split("")).println();</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>L(" "," "," ","T","a","e","h","i","i","s","s","s","t","t")</pre> |
<pre>L(" "," "," ","T","a","e","h","i","i","s","s","s","t","t")</pre> |
||
=={{header|ZX Spectrum Basic}}== |
=={{header|ZX Spectrum Basic}}== |
||
< |
<syntaxhighlight lang="zxbasic">5000 CLS |
||
5002 LET a$="": FOR f=1 TO 64: LET a$=a$+CHR$ (32+INT (RND*96)): NEXT f |
5002 LET a$="": FOR f=1 TO 64: LET a$=a$+CHR$ (32+INT (RND*96)): NEXT f |
||
5004 PRINT a$; AT 10,0;"ZigZag BubbleSORT" |
5004 PRINT a$; AT 10,0;"ZigZag BubbleSORT" |
||
Line 7,108: | Line 7,108: | ||
5064 IF d AND i<la THEN GO TO 5020 |
5064 IF d AND i<la THEN GO TO 5020 |
||
5072 PRINT AT 12,0;a$ |
5072 PRINT AT 12,0;a$ |
||
9000 STOP </ |
9000 STOP </syntaxhighlight> |
||
The traditional solution: |
The traditional solution: |
||
< |
<syntaxhighlight lang="zxbasic"> 10 LET siz=32 |
||
20 DIM d$(siz) |
20 DIM d$(siz) |
||
30 REM Populate d$ |
30 REM Populate d$ |
||
Line 7,122: | Line 7,122: | ||
90 NEXT i |
90 NEXT i |
||
100 IF unSorted THEN LET siz=siz-1: GO TO 60 |
100 IF unSorted THEN LET siz=siz-1: GO TO 60 |
||
110 PRINT d$</ |
110 PRINT d$</syntaxhighlight> |
||
{{omit from|GUISS}} |
{{omit from|GUISS}} |