Sort three variables: Difference between revisions
(better?) |
|||
(151 intermediate revisions by 71 users not shown) | |||
Line 3: | Line 3: | ||
{{Sorting Algorithm}} |
{{Sorting Algorithm}} |
||
;Task: |
;Task: |
||
Sort (the values of) three variables ('''X''', '''Y''', and '''Z''') that contain any value (numbers and/or literals). |
Sort (the values of) three variables ('''X''', '''Y''', and '''Z''') that contain any value (numbers and/or literals). |
||
If that isn't possible in your language, then just sort numbers (and note if they can be floating point, integer, or other). |
If that isn't possible in your language, then just sort numbers (and note if they can be floating point, integer, or other). |
||
I.E.: (for the three variables '''x''', '''y''', and '''z'''), where: |
I.E.: (for the three variables '''x''', '''y''', and '''z'''), where: |
||
Line 20: | Line 18: | ||
z = 'lions, tigers, and' |
z = 'lions, tigers, and' |
||
<!-- Care was taken to use a leading lowercase letter so that EBCDIC and ASCII machines sort the literals in the same order. |
<!-- Care was taken to use a leading lowercase letter so that EBCDIC and ASCII machines sort the literals in the same order. {Gerard Schildberger} !--> |
||
For numeric value sorting, use: |
For numeric value sorting, use: |
||
I.E.: (for the three variables '''x''', '''y''', and '''z'''), where: |
I.E.: (for the three variables '''x''', '''y''', and '''z'''), where: |
||
x = 77444 |
x = 77444 |
||
y = -12 |
y = -12 |
||
z = 0 |
z = 0 |
||
After sorting, the three variables would hold: |
After sorting, the three variables would hold: |
||
x = -12 |
x = -12 |
||
Line 37: | Line 31: | ||
The variables should contain some form of a number, but specify if the algorithm |
The variables should contain some form of a number, but specify if the algorithm |
||
used can be for floating point or integers. Note any limitations. |
used can be for floating point or integers. Note any limitations. |
||
The values may or may not be unique. |
The values may or may not be unique. |
||
The method used for sorting can be any algorithm; the goal is to use the most idiomatic in the computer programming language used. |
The method used for sorting can be any algorithm; the goal is to use the most idiomatic in the computer programming language used. |
||
Line 48: | Line 40: | ||
One algorithm could be: |
One algorithm could be: |
||
<big><big>•</big></big> store the three variables '''x''', '''y''', and '''z''' |
|||
into an array (or a list) '''A''' |
into an array (or a list) '''A''' |
||
|
|||
<big><big>•</big></big> sort (the three elements of) the array '''A''' |
|||
|
|||
<big><big>•</big></big> extract the three elements from the array and place them in the |
|||
variables '''x''', '''y''', and '''z''' in order of extraction |
|||
Θ sort (the three elements of) the array '''A''' |
|||
Θ extract the three elements from the array and place them in the |
|||
Another algorithm (only for numeric values): |
|||
variables '''x''', '''y''', and '''z''' in order of extraction |
|||
x= 77444 |
|||
y= -12 |
|||
z= 0 |
|||
low= x |
|||
mid= y |
|||
high= z |
|||
x= min(low, mid, high) /*determine the lowest value of X,Y,Z. */ |
|||
z= max(low, mid, high) /* " " highest " " " " " */ |
|||
y= low + mid + high - x - z /* " " middle " " " " " */ |
|||
Show the results of the sort here on this page using at least the values of those shown above. |
Show the results of the sort here on this page using at least the values of those shown above. |
||
<br><br> |
<br><br> |
||
=={{header|11l}}== |
|||
<syntaxhighlight lang="11l">V x = 77444 |
|||
V y = -12 |
|||
V z = 0 |
|||
(x, y, z) = tuple_sorted((x, y, z)) |
|||
print(x‘ ’y‘ ’z) |
|||
V xs = ‘lions, tigers, and’ |
|||
V ys = ‘bears, oh my!’ |
|||
V zs = ‘(from the "Wizard of OZ")’ |
|||
(xs, ys, zs) = sorted([xs, ys, zs]) |
|||
print(xs"\n"ys"\n"zs)</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
-12 0 77444 |
|||
(from the "Wizard of OZ") |
|||
bears, oh my! |
|||
lions, tigers, and |
|||
</pre> |
|||
=={{header|8086 Assembly}}== |
|||
===Sorting Unsigned Integers=== |
|||
<syntaxhighlight lang="asm">mov ax,6FFFh |
|||
mov bx,3456h |
|||
mov cx,0 |
|||
;We'll consider these sorted when ax <= bx <= cx. |
|||
SortRegisters proc |
|||
cmp ax,bx |
|||
jbe continue |
|||
;if we got here, ax > bx. We don't know the relationship between bx and cx at this time. |
|||
cmp ax,cx |
|||
jbe swap_ax_and_bx |
|||
;if we got here, ax > bx, and bx > cx. Therefore all we need to do is swap ax and cx, and we're done. |
|||
xchg ax,cx |
|||
jmp endOfProc |
|||
swap ax_and_bx: |
|||
;if we got here, ax > bx, and ax <= cx. So all we have to do is swap ax and bx, and we're done |
|||
xchg ax,bx |
|||
jmp end ;back to top |
|||
continue: ;if we got here, ax <= bx. |
|||
cmp bx,cx |
|||
jbe end |
|||
;if we got here, ax <= bx, and bx > cx. Therefore all we need to do is swap bx and cx, and we're done. |
|||
xchg bx,cx |
|||
endOfProc: ;if we got here, ax <= bx, and bx <= cx. Therefore, ax <= bx <=cx and we are done. |
|||
; |
|||
SortRegisters endp </syntaxhighlight> |
|||
=={{header|Ada}}== |
|||
<syntaxhighlight lang="ada">with Ada.Text_IO; |
|||
with Ada.Strings.Unbounded; |
|||
procedure Sort_Three is |
|||
generic |
|||
type Element_Type is private; |
|||
with function "<" (Left, Right : in Element_Type) return Boolean; |
|||
procedure Generic_Sort (X, Y, Z : in out Element_Type); |
|||
procedure Generic_Sort (X, Y, Z : in out Element_Type) |
|||
is |
|||
procedure Swap (Left, Right : in out Element_Type) is |
|||
T : constant Element_Type := Left; |
|||
begin |
|||
Left := Right; |
|||
Right := T; |
|||
end Swap; |
|||
begin |
|||
if Y < X then Swap (X, Y); end if; |
|||
if Z < Y then Swap (Y, Z); end if; |
|||
if Y < X then Swap (X, Y); end if; |
|||
end Generic_Sort; |
|||
procedure Test_Unbounded_Sort is |
|||
use Ada.Text_IO; |
|||
use Ada.Strings.Unbounded; |
|||
X : Unbounded_String := To_Unbounded_String ("lions, tigers, and"); |
|||
Y : Unbounded_String := To_Unbounded_String ("bears, oh my!"); |
|||
Z : Unbounded_String := To_Unbounded_String ("(from the ""Wizard of OZ"")"); |
|||
procedure Sort is |
|||
new Generic_Sort (Unbounded_String, "<"); |
|||
begin |
|||
Sort (X, Y, Z); |
|||
Put_Line (To_String (X)); |
|||
Put_Line (To_String (Y)); |
|||
Put_Line (To_String (Z)); |
|||
New_Line; |
|||
End Test_Unbounded_Sort; |
|||
procedure Test_Integer_Sort is |
|||
use Ada.Text_IO; |
|||
procedure Sort is |
|||
new Generic_Sort (Integer, "<"); |
|||
X : Integer := 77444; |
|||
Y : Integer := -12; |
|||
Z : Integer := 0; |
|||
begin |
|||
Sort (X, Y, Z); |
|||
Put_Line (X'Image); |
|||
Put_Line (Y'Image); |
|||
Put_Line (Z'Image); |
|||
New_Line; |
|||
end Test_Integer_Sort; |
|||
begin |
|||
Test_Unbounded_Sort; |
|||
Test_Integer_Sort; |
|||
end Sort_Three;</syntaxhighlight> |
|||
{{out}} |
|||
<pre>(from the "Wizard of OZ") |
|||
bears, oh my! |
|||
lions, tigers, and |
|||
-12 |
|||
0 |
|||
77444</pre> |
|||
=={{header|Aime}}== |
|||
<syntaxhighlight lang="aime">integer a, b, c; |
|||
index i; |
|||
text x, y, z; |
|||
record r; |
|||
x = "lions, tigers, and"; |
|||
y = "bears, oh my!"; |
|||
z = "(from the \"Wizard of OZ\")"; |
|||
r.fit(x, x, y, y, z, z); |
|||
x = r.rf_pick; |
|||
y = r.rf_pick; |
|||
z = r.rf_pick; |
|||
o_form("~\n~\n~\n", x, y, z); |
|||
a = 77444; |
|||
b = -12; |
|||
c = 0; |
|||
i.fit(a, a, b, b, c, c); |
|||
a = i.if_pick; |
|||
b = i.if_pick; |
|||
c = i.if_pick; |
|||
o_form("~\n~\n~\n", a, b, c);</syntaxhighlight> |
|||
{{out}} |
|||
<pre>(from the "Wizard of OZ") |
|||
bears, oh my! |
|||
lions, tigers, and |
|||
-12 |
|||
0 |
|||
77444</pre> |
|||
=={{header|ALGOL 68}}== |
=={{header|ALGOL 68}}== |
||
Line 66: | Line 241: | ||
<br> |
<br> |
||
As the task only requires sorting three values, we use a simple, three-element specific sort routine. |
As the task only requires sorting three values, we use a simple, three-element specific sort routine. |
||
< |
<syntaxhighlight lang="algol68">BEGIN |
||
# MODE that can hold integers and strings - would need to be extended to # |
# MODE that can hold integers and strings - would need to be extended to # |
||
# allow for other types # |
# allow for other types # |
||
Line 115: | Line 290: | ||
sort 3( x, y, z ); |
sort 3( x, y, z ); |
||
print( ( x, newline, y, newline, z, newline ) ) |
print( ( x, newline, y, newline, z, newline ) ) |
||
END</ |
END</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>(from the "Wizard of OZ") |
|||
<pre> |
|||
(from the "Wizard of OZ") |
|||
bears, oh my! |
bears, oh my! |
||
lions, tigers, and |
lions, tigers, and |
||
-12 |
-12 |
||
+0 |
+0 |
||
+77444 |
+77444</pre> |
||
=={{header|Amazing Hopper}}== |
|||
<syntaxhighlight lang="c"> |
|||
#include <basico.h> |
|||
algoritmo |
|||
x = 77444, y = -12.5, z = 0 |
|||
low=x, midd=y, high=z |
|||
imprimir("BEFORE:\nX = ",x, " Y = ",y, " Z = ",z,NL) |
|||
#basic{ |
|||
x = min( min( low,midd),high) |
|||
z = max( max( low,midd),high) |
|||
y = low + midd + high - x - z |
|||
} |
|||
imprimir("\nAFTER:\nX = ",x, " Y = ",y, " Z = ",z,NL,NL) |
|||
x = "lions, tigers, and" |
|||
y = "bears, oh my!" |
|||
z = "(from the \"Wizard of OZ\")" |
|||
imprimir("BEFORE:\nX = ",x, "\nY = ",y, "\nZ = ",z,NL) |
|||
#(x > y), entonces { intercambiar( x,y) } |
|||
#(y > z), entonces { |
|||
intercambiar (y,z ) |
|||
#(x > y), entonces { intercambiar( x,y ) } |
|||
} |
|||
imprimir("\nAFTER:\nX = ",x, "\nY = ",y, "\nZ = ",z,NL,NL) |
|||
p = {} |
|||
'"lions, tigers, and",77444,"bears, oh my!",-12.7,0,"(from the \"Wizard of OZ\")"' |
|||
enlistar en 'p' |
|||
fijar separador 'NL' |
|||
imprimir("BEFORE:\n",p,NL) |
|||
matriz.ordenar(p) |
|||
imprimir("\nAFTER:\n",p,NL) |
|||
terminar |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
$ hopper3 basica/sort3var.bas |
|||
BEFORE: |
|||
X = 77444 Y = -12.500000 Z = 0 |
|||
AFTER: |
|||
X = -12.500000 Y = 0.000000 Z = 77444.000000 |
|||
BEFORE: |
|||
X = lions, tigers, and |
|||
Y = bears, oh my! |
|||
Z = (from the "Wizard of OZ") |
|||
AFTER: |
|||
X = (from the "Wizard of OZ") |
|||
Y = bears, oh my! |
|||
Z = lions, tigers, and |
|||
BEFORE: |
|||
lions, tigers, and |
|||
77444 |
|||
bears, oh my! |
|||
-12.700000 |
|||
0 |
|||
(from the "Wizard of OZ") |
|||
AFTER: |
|||
(from the "Wizard of OZ") |
|||
bears, oh my! |
|||
lions, tigers, and |
|||
-12.700000 |
|||
0 |
|||
77444 |
|||
</pre> |
</pre> |
||
=={{header|APL}}== |
|||
Works in [[Dyalog APL]]. Assumes x,y,z are already defined. |
|||
<syntaxhighlight lang="apl">x y z←{⍵[⍋⍵]}x y z</syntaxhighlight> |
|||
Uses destructuring assignment syntax. |
|||
=={{header|AppleScript}}== |
|||
<syntaxhighlight lang="applescript">set x to "lions, tigers, and" |
|||
set y to "bears, oh my!" |
|||
set z to "(from the \"Wizard of OZ\")" |
|||
if (x > y) then set {x, y} to {y, x} |
|||
if (y > z) then |
|||
set {y, z} to {z, y} |
|||
if (x > y) then set {x, y} to {y, x} |
|||
end if |
|||
return {x, y, z}</syntaxhighlight> |
|||
{{output}} |
|||
<pre>{"(from the \"Wizard of OZ\")", "bears, oh my!", "lions, tigers, and"}</pre> |
|||
<syntaxhighlight lang="applescript">set x to 77444 |
|||
set y to -12 |
|||
set z to 0 |
|||
if (x > y) then set {x, y} to {y, x} |
|||
if (y > z) then |
|||
set {y, z} to {z, y} |
|||
if (x > y) then set {x, y} to {y, x} |
|||
end if |
|||
return {x, y, z}</syntaxhighlight> |
|||
{{output}} |
|||
<pre>{-12, 0, 77444}</pre> |
|||
Longer, but more efficiently: |
|||
<syntaxhighlight lang="applescript">set x to "lions, tigers, and" |
|||
set y to "bears, oh my!" |
|||
set z to "(from the \"Wizard of OZ\")" |
|||
tell x |
|||
if (it > y) then |
|||
set x to y |
|||
set y to it |
|||
end if |
|||
end tell |
|||
tell z |
|||
if (it < y) then |
|||
set z to y |
|||
if (it < x) then |
|||
set y to x |
|||
set x to it |
|||
else |
|||
set y to it |
|||
end if |
|||
end if |
|||
end tell |
|||
return {x, y, z}</syntaxhighlight> |
|||
=={{header|Arturo}}== |
|||
<syntaxhighlight lang="rebol">x: {lions, tigers, and} |
|||
y: {bears, oh my!} |
|||
z: {(from the "Wizard of OZ")} |
|||
print join.with:"\n" sort @[x y z] |
|||
x: 125 |
|||
y: neg 2 |
|||
z: pi |
|||
print sort @[x y z]</syntaxhighlight> |
|||
{{out}} |
|||
<pre>(from the "Wizard of OZ") |
|||
bears, oh my! |
|||
lions, tigers, and |
|||
-2 3.141592653589793 125</pre> |
|||
=={{header|AutoHotkey}}== |
|||
<syntaxhighlight lang="autohotkey">SortThreeVariables(ByRef x,ByRef y,ByRef z){ |
|||
obj := [] |
|||
for k, v in (var := StrSplit("x,y,z", ",")) |
|||
obj[%v%] := true |
|||
for k, v in obj |
|||
temp := var[A_Index], %temp% := k |
|||
}</syntaxhighlight> |
|||
Examples:<syntaxhighlight lang="autohotkey">x = lions, tigers, and |
|||
y = bears, oh my! |
|||
z = (from the "Wizard of OZ") |
|||
SortThreeVariables(x,y,z) |
|||
MsgBox % x "`n" y "`n" z |
|||
x = 77444 |
|||
y = -12 |
|||
z = 0 |
|||
SortThreeVariables(x,y,z) |
|||
MsgBox % x "`n" y "`n" z |
|||
return</syntaxhighlight> |
|||
Outputs:<pre>--------------------------- |
|||
(from the "Wizard of OZ") |
|||
bears, oh my! |
|||
lions, tigers, and |
|||
--------------------------- |
|||
-12 |
|||
0 |
|||
77444 |
|||
---------------------------</pre> |
|||
=={{header|BCPL}}== |
|||
BCPL is typeless: every variable is simply a machine word, and it is the operators |
|||
that are used that decide how to treat their input. Therefore, this function |
|||
uses an external comparator function to decide how the three variables should |
|||
be ordered. |
|||
The code below uses <code>sort3</code> to sort both integers and strings |
|||
(i.e., pointers to vectors of characters packed into machine words). |
|||
To make it work with floating-point numbers, on a compiler that supports them, |
|||
all one would need to do is define a third comparator. |
|||
<syntaxhighlight lang="bcpl">get "libhdr" |
|||
// Sort 3 variables using a comparator. |
|||
// X, Y and Z are pointers. |
|||
let sort3(comp, x, y, z) be |
|||
$( sort2(comp, x, y) |
|||
sort2(comp, x, z) |
|||
sort2(comp, y, z) |
|||
$) |
|||
and sort2(comp, x, y) be |
|||
if comp(!x, !y) > 0 |
|||
$( let t = !x |
|||
!x := !y |
|||
!y := t |
|||
$) |
|||
// Integer and string comparators |
|||
let intcomp(x, y) = x - y |
|||
let strcomp(x, y) = valof |
|||
$( for i=1 to min(x%0, y%0) |
|||
unless x%i = y%i |
|||
resultis intcomp(x%i, y%i) |
|||
resultis intcomp(x%0, y%0) |
|||
$) |
|||
and min(x, y) = x < y -> x, y |
|||
// Run the function on both ints and strings |
|||
let start() be |
|||
$( printAndSort(writen, intcomp, 7444, -12, 0) |
|||
printAndSort(writes, strcomp, |
|||
"lions, tigers, and", |
|||
"bears, oh my!", |
|||
"(from the *"Wizard of OZ*")") |
|||
$) |
|||
// Print the 3 values, sort them, and print them again |
|||
and printAndSort(printfn, comp, x, y, z) be |
|||
$( print3(printfn, x, y, z) ; writes("*N") |
|||
sort3(comp, @x, @y, @z) |
|||
print3(printfn, x, y, z) ; writes("------*N") |
|||
$) |
|||
// Print 3 values given printing function |
|||
and print3(printfn, x, y, z) be |
|||
$( writes("X = ") ; printfn(x) ; wrch('*N') |
|||
writes("Y = ") ; printfn(y) ; wrch('*N') |
|||
writes("Z = ") ; printfn(z) ; wrch('*N') |
|||
$)</syntaxhighlight> |
|||
{{out}} |
|||
<pre>X = 7444 |
|||
Y = -12 |
|||
Z = 0 |
|||
X = -12 |
|||
Y = 0 |
|||
Z = 7444 |
|||
------ |
|||
X = lions, tigers, and |
|||
Y = bears, oh my! |
|||
Z = (from the "Wizard of OZ") |
|||
X = (from the "Wizard of OZ") |
|||
Y = bears, oh my! |
|||
Z = lions, tigers, and |
|||
------</pre> |
|||
=={{header|C}}== |
|||
Although C does not have a generic catch-all variable type, strings or arrays of characters can be used ( or misused ) to simulate the effect. Strings are often used to process arbitrarily large or small numbers which can't be represented by the C Standard Library. Strings are thus used for this task to accept whatever the user enters. Each entry is treated as a string and is scanned. If any one of them contains a single 'non-number' character, then the whole set is treated as a set of strings. |
|||
The first implementation is generic and can be used for any entries ( integer, floating point, strings). The second one is specific to the task and only sorts integers. |
|||
===Generic Implementation=== |
|||
<syntaxhighlight lang="c"> |
|||
#include<string.h> |
|||
#include<stdlib.h> |
|||
#include<stdio.h> |
|||
#define MAX 3 |
|||
int main() |
|||
{ |
|||
char values[MAX][100],tempStr[100]; |
|||
int i,j,isString=0; |
|||
double val[MAX],temp; |
|||
for(i=0;i<MAX;i++){ |
|||
printf("Enter %d%s value : ",i+1,(i==0)?"st":((i==1)?"nd":"rd")); |
|||
fgets(values[i],100,stdin); |
|||
for(j=0;values[i][j]!=00;j++){ |
|||
if(((values[i][j]<'0' || values[i][j]>'9') && (values[i][j]!='.' ||values[i][j]!='-'||values[i][j]!='+')) |
|||
||((values[i][j]=='.' ||values[i][j]=='-'||values[i][j]=='+')&&(values[i][j+1]<'0' || values[i][j+1]>'9'))) |
|||
isString = 1; |
|||
} |
|||
} |
|||
if(isString==0){ |
|||
for(i=0;i<MAX;i++) |
|||
val[i] = atof(values[i]); |
|||
} |
|||
for(i=0;i<MAX-1;i++){ |
|||
for(j=i+1;j<MAX;j++){ |
|||
if(isString==0 && val[i]>val[j]){ |
|||
temp = val[j]; |
|||
val[j] = val[i]; |
|||
val[i] = temp; |
|||
} |
|||
else if(values[i][0]>values[j][0]){ |
|||
strcpy(tempStr,values[j]); |
|||
strcpy(values[j],values[i]); |
|||
strcpy(values[i],tempStr); |
|||
} |
|||
} |
|||
} |
|||
for(i=0;i<MAX;i++) |
|||
isString==1?printf("%c = %s",'X'+i,values[i]):printf("%c = %lf",'X'+i,val[i]); |
|||
return 0; |
|||
} |
|||
</syntaxhighlight>The output shows three test cases, two as specified in the task, and one which mixes numbers and strings. The output is sorted considering all of them as strings in that case. |
|||
<pre> |
|||
Enter 1st value : 77444 |
|||
Enter 2nd value : -12 |
|||
Enter 3rd value : 0 |
|||
X = -12 |
|||
Y = 0 |
|||
Z = 77444 |
|||
Enter 1st value : lions, tigers, and |
|||
Enter 2nd value : bears, oh my! |
|||
Enter 3rd value : (from the "Wizard of OZ") |
|||
X = (from the "Wizard of OZ") |
|||
Y = bears, oh my! |
|||
Z = lions, tigers, and |
|||
Enter 1st value : -12 |
|||
Enter 2nd value : bears, oh my! |
|||
Enter 3rd value : 77444 |
|||
X = -12 |
|||
Y = 77444 |
|||
Z = bears, oh my! |
|||
</pre> |
|||
===Task Specific Implementation=== |
|||
<syntaxhighlight lang="c"> |
|||
#include<stdio.h> |
|||
int main() |
|||
{ |
|||
int x = 77444,y=-12,z=0,temp; |
|||
printf("Before sorting :\nx = %d\ny = %d\nz = %d",x,y,z); |
|||
do{ |
|||
temp = x; |
|||
if(temp > y){ |
|||
x = y; |
|||
y = temp; |
|||
} |
|||
if(z < y){ |
|||
temp = y; |
|||
y = z; |
|||
z = temp; |
|||
} |
|||
}while(x>y || y>z); |
|||
printf("\nAfter sorting :\nx = %d\ny = %d\nz = %d",x,y,z); |
|||
return 0; |
|||
} |
|||
</syntaxhighlight> |
|||
Output : |
|||
<pre>Before sorting : |
|||
x = 77444 |
|||
y = -12 |
|||
z = 0 |
|||
After sorting : |
|||
x = -12 |
|||
y = 0 |
|||
z = 77444</pre> |
|||
=={{header|C sharp}}== |
=={{header|C sharp}}== |
||
{{works with|C sharp|7.0}} |
{{works with|C sharp|7.0}} |
||
< |
<syntaxhighlight lang="csharp">using System; |
||
public class Program |
public class Program |
||
{ |
{ |
||
public static void Main() |
public static void Main() |
||
{ |
{ |
||
(int x, int y, int z) = ( |
(int x, int y, int z) = (77444, -12, 0); |
||
//Sort directly: |
//Sort directly: |
||
Line 158: | Line 726: | ||
if (b.CompareTo(c) > 0) (b, c) = (c, b); |
if (b.CompareTo(c) > 0) (b, c) = (c, b); |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre>(-12, 0, 77444) |
||
((from the 'Wizard of OZ'), bears, oh my!, lions, tigers, and)</pre> |
|||
(1, 2, 5) |
|||
((from the 'Wizard of OZ'), bears, oh my!, lions, tigers, and) |
|||
</pre> |
|||
=={{header|C++}}== |
=={{header|C++}}== |
||
<syntaxhighlight lang="cpp">#include <algorithm> |
|||
<lang Cpp> |
|||
#include <iostream> |
#include <iostream> |
||
#include <string> |
#include <string> |
||
#include <vector> |
#include <vector> |
||
template < class T > |
template < class T > |
||
void sort3( T& x, T& y, T& z) { |
void sort3( T& x, T& y, T& z) { |
||
std::vector<T> v; |
std::vector<T> v{x, y, z}; |
||
v. |
std::sort(v.begin(), v.end()); |
||
bool b = true; |
|||
while( b ) { |
|||
b = false; |
|||
for( size_t i = 0; i < v.size() - 1; i++ ) { |
|||
if( v[i] > v[i+1] ) { |
|||
T t = v[i]; |
|||
v[i] = v[i + 1]; |
|||
v[i + 1] = t; |
|||
b = true; |
|||
} |
|||
} |
|||
} |
|||
x = v[0]; y = v[1]; z = v[2]; |
x = v[0]; y = v[1]; z = v[2]; |
||
} |
} |
||
int main( |
int main() { |
||
int xi = 77444, yi = -12, zi = 0; |
int xi = 77444, yi = -12, zi = 0; |
||
sort3( xi, yi, zi ); |
sort3( xi, yi, zi ); |
||
std::cout << xi << "\n" << yi << "\n" << zi << "\n\n"; |
std::cout << xi << "\n" << yi << "\n" << zi << "\n\n"; |
||
std::string xs, ys, zs; |
std::string xs, ys, zs; |
||
xs = "lions, tigers, and"; |
xs = "lions, tigers, and"; |
||
Line 200: | Line 754: | ||
sort3( xs, ys, zs ); |
sort3( xs, ys, zs ); |
||
std::cout << xs << "\n" << ys << "\n" << zs << "\n\n"; |
std::cout << xs << "\n" << ys << "\n" << zs << "\n\n"; |
||
float xf = 11.3f, yf = -9.7f, zf = 11.17f; |
float xf = 11.3f, yf = -9.7f, zf = 11.17f; |
||
sort3( xf, yf, zf ); |
sort3( xf, yf, zf ); |
||
std::cout << xf << "\n" << yf << "\n" << zf << "\n\n"; |
std::cout << xf << "\n" << yf << "\n" << zf << "\n\n"; |
||
return 0; |
|||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre>-12 |
||
-12 |
|||
0 |
0 |
||
77444 |
77444 |
||
(from the "Wizard of OZ") |
(from the "Wizard of OZ") |
||
bears, oh my! |
bears, oh my! |
||
lions, tigers, and |
lions, tigers, and |
||
-9.7 |
-9.7 |
||
11.17 |
11.17 |
||
11.3 |
11.3</pre> |
||
=={{header|CLU}}== |
|||
<syntaxhighlight lang="clu">% Sort three variables. |
|||
% The variables must all be of the same type, and the type |
|||
% must implement the less-than comparator. |
|||
sort_three = proc [T: type] (x,y,z: T) returns (T,T,T) |
|||
where T has lt: proctype (T,T) returns (bool) |
|||
if y<x then x,y := y,x end |
|||
if z<y then y,z := z,y end |
|||
if y<x then x,y := y,z end |
|||
return(x,y,z) |
|||
end sort_three |
|||
% Test it out on three values, when also given a type and a |
|||
% formatter. |
|||
example = proc [T: type] (x,y,z: T, fmt: proctype (T) returns (string)) |
|||
where T has lt: proctype (T,T) returns (bool) |
|||
po: stream := stream$primary_output() |
|||
% Print the variables |
|||
stream$putl(po, "x=" || fmt(x) |
|||
|| " y=" || fmt(y) |
|||
|| " z=" || fmt(z)) |
|||
% Sort them |
|||
x,y,z := sort_three[T](x,y,z) |
|||
% Print them again |
|||
stream$putl(po, "x=" || fmt(x) |
|||
|| " y=" || fmt(y) |
|||
|| " z=" || fmt(z) |
|||
|| "\n") |
|||
end example |
|||
% And then we also need formatters, since those are not standardized |
|||
% such as '<' is. |
|||
fmt_real = proc (n: real) returns (string) |
|||
return(f_form(n,2,2)) |
|||
end fmt_real |
|||
fmt_str = proc (s: string) returns (string) |
|||
return( "'" || s || "'" ) |
|||
end fmt_str |
|||
% Test it out on values of each type |
|||
start_up = proc () |
|||
example[int] (77444, -12, 0, int$unparse) |
|||
example[real] (11.3, -9.7, 11.17, fmt_real) |
|||
example[string] ("lions, tigers and", "bears, oh my!", |
|||
"(from the \"Wizard of Oz\")", fmt_str) |
|||
end start_up</syntaxhighlight> |
|||
{{out}} |
|||
<pre>x=77444 y=-12 z=0 |
|||
x=-12 y=0 z=77444 |
|||
x=11.30 y=-9.70 z=11.17 |
|||
x=-9.70 y=11.17 z=11.30 |
|||
x='lions, tigers and' y='bears, oh my!' z='(from the "Wizard of Oz")' |
|||
x='(from the "Wizard of Oz")' y='lions, tigers and' z='lions, tigers and'</pre> |
|||
=={{header|COBOL}}== |
|||
<syntaxhighlight lang="cobol"> program-id. 3var. |
|||
data division. |
|||
working-storage section. |
|||
1 n binary pic 9(4). |
|||
1 num pic -(7)9. |
|||
1 a1 pic x(32) value "lions, tigers, and". |
|||
1 a2 pic x(32) value "bears, oh my!". |
|||
1 a3 pic x(32) value "(from the ""Wizard of OZ"")". |
|||
1 n1 pic x(8) value "77444". |
|||
1 n2 pic x(8) value "-12". |
|||
1 n3 pic x(8) value "0". |
|||
1 alpha-table. |
|||
2 alpha-entry occurs 3 pic x(32). |
|||
1 numeric-table. |
|||
2 numeric-entry occurs 3 pic s9(8). |
|||
1 filler value "x = y = z = ". |
|||
2 lead-in occurs 3 pic x(4). |
|||
procedure division. |
|||
begin. |
|||
move a1 to alpha-entry (1) |
|||
move a2 to alpha-entry (2) |
|||
move a3 to alpha-entry (3) |
|||
sort alpha-entry ascending alpha-entry |
|||
perform varying n from 1 by 1 |
|||
until n > 3 |
|||
display lead-in (n) alpha-entry (n) |
|||
end-perform |
|||
display space |
|||
compute numeric-entry (1) = function numval (n1) |
|||
compute numeric-entry (2) = function numval (n2) |
|||
compute numeric-entry (3) = function numval (n3) |
|||
sort numeric-entry ascending numeric-entry |
|||
perform varying n from 1 by 1 |
|||
until n > 3 |
|||
move numeric-entry (n) to num |
|||
display lead-in (n) num |
|||
end-perform |
|||
stop run |
|||
. |
|||
end program 3var.</syntaxhighlight> |
|||
{{out}} |
|||
<pre>x = (from the "Wizard of OZ") |
|||
y = bears, oh my! |
|||
z = lions, tigers, and |
|||
x = -12 |
|||
y = 0 |
|||
z = 77444</pre> |
|||
=={{header|Cowgol}}== |
|||
<syntaxhighlight lang="cowgol">include "cowgol.coh"; |
|||
# Sort 3 values |
|||
sub sort3(a: int32, b: int32, c: int32): (x: int32, y: int32, z: int32) is |
|||
sub sort2(a: int32, b: int32): (x: int32, y: int32) is |
|||
if a > b then |
|||
x := b; |
|||
y := a; |
|||
else |
|||
x := a; |
|||
y := b; |
|||
end if; |
|||
end sub; |
|||
x := a; |
|||
y := b; |
|||
z := c; |
|||
(x, y) := sort2(x, y); |
|||
(x, z) := sort2(x, z); |
|||
(y, z) := sort2(y, z); |
|||
end sub; |
|||
# Print 3 values |
|||
sub print3(a: int32, b: int32, c: int32) is |
|||
sub print1(a: int32) is |
|||
var buf: uint8[10]; |
|||
[IToA(a, 10, &buf[0])] := 0; |
|||
print(&buf[0]); |
|||
print_char(' '); |
|||
end sub; |
|||
print1(a); |
|||
print1(b); |
|||
print1(c); |
|||
print_nl(); |
|||
end sub; |
|||
var x: int32 := 77444; |
|||
var y: int32 := -12; |
|||
var z: int32 := 0; |
|||
# Print 3 values before sorting |
|||
print3(x, y, z); |
|||
# Sort 3 values |
|||
(x, y, z) := sort3(x, y, z); |
|||
# Print 3 values after sorting |
|||
print3(x, y, z);</syntaxhighlight> |
|||
{{out}} |
|||
<pre>77444 -12 0 |
|||
-12 0 77444</pre> |
|||
=={{header|D}}== |
|||
<syntaxhighlight lang="d">import std.stdio; |
|||
void main() { |
|||
driver(77444, -12, 0); |
|||
driver("lions, tigers, and", "bears, oh my!", "(from the \"Wizard of OZ\")"); |
|||
} |
|||
void driver(T)(T x, T y, T z) { |
|||
writeln("BEFORE: x=[", x, "]; y=[", y, "]; z=[", z, "]"); |
|||
sort3Var(x,y,z); |
|||
writeln("AFTER: x=[", x, "]; y=[", y, "]; z=[", z, "]"); |
|||
} |
|||
void sort3Var(T)(ref T x, ref T y, ref T z) |
|||
out { |
|||
assert(x<=y); |
|||
assert(x<=z); |
|||
assert(y<=z); |
|||
} |
|||
body { |
|||
import std.algorithm : swap; |
|||
if (x < y) { |
|||
if (z < x) { |
|||
swap(x,z); |
|||
} |
|||
} else if (y < z) { |
|||
swap(x,y); |
|||
} else { |
|||
swap(x,z); |
|||
} |
|||
if (z<y) { |
|||
swap(y,z); |
|||
} |
|||
}</syntaxhighlight> |
|||
{{out}} |
|||
<pre>BEFORE: x=[77444]; y=[-12]; z=[0] |
|||
AFTER: x=[-12]; y=[0]; z=[77444] |
|||
BEFORE: x=[lions, tigers, and]; y=[bears, oh my!]; z=[(from the "Wizard of OZ")] |
|||
AFTER: x=[(from the "Wizard of OZ")]; y=[bears, oh my!]; z=[lions, tigers, and]</pre> |
|||
=={{header|EasyLang}}== |
|||
<syntaxhighlight lang=easylang> |
|||
proc sort3 . a b c . |
|||
if a > c |
|||
swap a c |
|||
. |
|||
if b > c |
|||
swap b c |
|||
. |
|||
if a > b |
|||
swap a b |
|||
. |
|||
. |
|||
x = 77444 |
|||
y = -12 |
|||
z = 0 |
|||
sort3 x y z |
|||
print x & " " & y & " " & z |
|||
# |
|||
proc sort3str . a$ b$ c$ . |
|||
if strcmp a$ c$ > 0 |
|||
swap a$ c$ |
|||
. |
|||
if strcmp b$ c$ > 0 |
|||
swap b$ c$ |
|||
. |
|||
if strcmp a$ b$ > 0 |
|||
swap a$ b$ |
|||
. |
|||
. |
|||
x$ = "lions, tigers, and" |
|||
y$ = "bears, oh my!" |
|||
z$ = "(from the \"Wizard of OZ\")" |
|||
sort3str x$ y$ z$ |
|||
print x$ |
|||
print y$ |
|||
print z$ |
|||
</syntaxhighlight> |
|||
=={{header|EDSAC order code}}== |
|||
<syntaxhighlight lang="edsac"> |
|||
[Sort three variables, for Rosetta Code. |
|||
EDSAC, Initial Orders 2] |
|||
[--------------------------------------------------------------------------- |
|||
Sorts three 35-bit variables x, y, x, stored at 0#V, 2#V, 4#V respectively. |
|||
Uses the algortihm: |
|||
if x > z then swap( x,z) |
|||
if y > z then swap( y,z) |
|||
if x > y then swap( x,y) |
|||
At most two swaps are carried out in any particular case. |
|||
----------------------------------------------------------------------------] |
|||
[Arrange the storage] |
|||
T47K P96F [M parameter: main routine] |
|||
T55K P128F [V parameter: variables to be sorted] |
|||
[Compressed form of library subroutine R2. |
|||
Reads integers at load time and is then overwritten.] |
|||
GKT20FVDL8FA40DUDTFI40FA40FS39FG@S2FG23FA5@T5@E4@E13Z |
|||
T#V [tell R2 where to store integers] |
|||
[EDIT: List of 35-bit integers separated by 'F', list terminated by '#TZ'.] |
|||
987654321F500000000F123456789#TZ |
|||
[Main routine] |
|||
E25K TM GK |
|||
[0] A4#V S#V [accumulator := z - x] |
|||
E8@ [skip the swap if x <= z] |
|||
TD [0D := z - x] |
|||
A#V U4#V [z := x] |
|||
AD [acc := old z] |
|||
T#V [x := old z] |
|||
[8] TF [clear acc] |
|||
A4#V S2#V [acc := z - y] |
|||
E17@ [skip the swap if y <= z] |
|||
TD [0D := z - y] |
|||
A2#V U4#V [z := y] |
|||
AD [acc := old z] |
|||
T2#V [y := old z] |
|||
[17] TF [clear acc] |
|||
A2#V S#V [acc := y - x] |
|||
E26@ [skip the swap if x <= y] |
|||
TD [0D := y - x] |
|||
A#V U2#V [y := x] |
|||
AD [acc := old y] |
|||
T#V [x := old y] |
|||
[26] ZF [halt the machine] |
|||
EZ [define entry point] |
|||
PF [acc = 0 on entry] |
|||
[end] |
|||
</syntaxhighlight> |
|||
=={{header|Elena}}== |
|||
ELENA 6.x : |
|||
<syntaxhighlight lang="elena">import extensions; |
|||
sortThree(ref object a, ref object b, ref object c) |
|||
{ |
|||
if (a > b) { exchange(ref a, ref b) }; |
|||
if (a > c) { exchange(ref a, ref c) }; |
|||
if (b > c) { exchange(ref b, ref c) } |
|||
} |
|||
public program() |
|||
{ |
|||
var x := 5; |
|||
var y := 1; |
|||
var z := 2; |
|||
var a := "lions, tigers, and"; |
|||
var b := "bears, oh my!"; |
|||
var c := "(from the 'Wizard of OZ')"; |
|||
sortThree(ref x,ref y,ref z); |
|||
sortThree(ref a,ref b,ref c); |
|||
console.printLine(x,",",y,",",z); |
|||
console.printLine(a,",",b,",",c) |
|||
}</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
1,2,5 |
|||
(from the 'Wizard of OZ'),bears, oh my!,lions, tigers, and |
|||
</pre> |
</pre> |
||
=={{header|Elixir}}== |
|||
<syntaxhighlight lang="elixir">x = 'lions, tigers, and' |
|||
y = 'bears, oh my!' |
|||
z = '(from the "Wizard of OZ")' |
|||
[x, y, z] = Enum.sort([x, y, z]) |
|||
IO.puts "x = #{x}\ny = #{y}\nz = #{z}\n" |
|||
x = 77444 |
|||
y = -12 |
|||
z = 0 |
|||
[x, y, z] = Enum.sort([x, y, z]) |
|||
IO.puts "x = #{x}\ny = #{y}\nz = #{z}"</syntaxhighlight> |
|||
{{out}} |
|||
<pre>x = (from the "Wizard of OZ") |
|||
y = bears, oh my! |
|||
z = lions, tigers, and |
|||
x = -12 |
|||
y = 0 |
|||
z = 77444</pre> |
|||
=={{header|F_Sharp|F#}}== |
|||
<syntaxhighlight lang="fsharp"> let x = "lions, tigers, and" |
|||
let y = "bears, oh my!" |
|||
let z = """(from the "Wizard of OZ")""" |
|||
List.iter (printfn "%s") (List.sort [x;y;z]) |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre>(from the "Wizard of OZ") |
|||
bears, oh my! |
|||
lions, tigers, and</pre> |
|||
=={{header|Factor}}== |
|||
<syntaxhighlight lang="factor">USING: arrays io kernel prettyprint sequences sorting ; |
|||
IN: rosetta-code.sort-three |
|||
: sort3 ( b c a -- a b c ) 3array natural-sort first3 ; |
|||
"lions, tigers, and" |
|||
"bears, oh my!" |
|||
"(from the \"Wizard of OZ\")" |
|||
sort3 [ print ] tri@ |
|||
77444 -12 0 sort3 [ . ] tri@</syntaxhighlight> |
|||
{{out}} |
|||
<pre>(from the "Wizard of OZ") |
|||
bears, oh my! |
|||
lions, tigers, and |
|||
-12 |
|||
0 |
|||
77444</pre> |
|||
=={{header|FALSE}}== |
|||
FALSE supports neither floating point numbers nor strings. |
|||
<syntaxhighlight lang="false">{ [s]waps two variables. (varref; varref) → () } |
|||
[ |
|||
b: { loads the value at the top of the stack into b } |
|||
a: { loads the value at the top of the stack into a } |
|||
a;; t: { loads the value stored in the variable stored in a (hence the double dereference) into t } |
|||
b;; a;: { loads the value stored in the variable stored in b into the variable stored in a } |
|||
t; b;: { loads the value stored in t into the variable stored in b } |
|||
]s: |
|||
{ [p]rints the three variables. } |
|||
[ |
|||
"X = " x;. 10, |
|||
"Y = " y;. 10, |
|||
"Z = " z;. 10, |
|||
]p: |
|||
77444 x: |
|||
12_ y: |
|||
0 z: |
|||
p;! |
|||
{ if x > y, swap x and y } |
|||
x;y;> [xys;!] ? |
|||
{ if y > z, swap y and z } |
|||
y;z;> [yzs;!] ? |
|||
{ if x > y, swap x and y } |
|||
x;y;> [xys;!] ? |
|||
"After sorting: |
|||
" |
|||
p;!</syntaxhighlight> |
|||
{{out}} |
|||
<pre>X = 77444 |
|||
Y = -12 |
|||
Z = 0 |
|||
After sorting: |
|||
X = -12 |
|||
Y = 0 |
|||
Z = 77444</pre> |
|||
=={{header|FreeBASIC}}== |
|||
Shows the use of macros, which are type-agnostic (though you cannot mix string and numerical types). |
|||
<syntaxhighlight lang="freebasic">#macro sort_three( x, y, z ) |
|||
if x>y then swap x, y |
|||
if y>z then swap y, z |
|||
if x>y then swap x, y |
|||
#endmacro |
|||
'demonstrate this for strings |
|||
dim as string x = "lions, tigers, and" |
|||
dim as string y = "bears, oh my!" |
|||
dim as string z = "(from the ""Wizard of OZ"")" |
|||
sort_three(x,y,z) |
|||
print x |
|||
print y |
|||
print z : print |
|||
'demonstrate this for signed integers |
|||
dim as integer a = 77444 |
|||
dim as integer b = -12 |
|||
dim as integer c = 0 |
|||
sort_three(a,b,c) |
|||
print a |
|||
print b |
|||
print c</syntaxhighlight> |
|||
{{out}}<pre>(from the "Wizard of OZ") |
|||
bears, oh my! |
|||
lions, tigers, and |
|||
-12 |
|||
0 |
|||
77444</pre> |
|||
=={{header|Forth}}== |
|||
==={{header|Integers}}=== |
|||
In GNU Forth the machine's integers are the default data type. |
|||
It is straightforward to sort these on the Forth Data Stack. |
|||
<BR>Note: |
|||
Assigning the values to variables is simple however unless |
|||
storage in variables was needed to retain the values, they would |
|||
typically be used directly from the stack by a subsequent operation in the |
|||
program. |
|||
<syntaxhighlight lang="forth" lines>\ sort 3 integers |
|||
VARIABLE X VARIABLE Y VARIABLE Z |
|||
: VARS@ ( --- n n n) X @ Y @ Z @ ; \ read variables |
|||
: VARS! ( n n n -- ) Z ! Y ! X ! ; \ store variables |
|||
: ?SWAP ( a b -- a b) \ conditional swap |
|||
2DUP < IF SWAP THEN ; |
|||
: SORT3INTS ( a b c -- c b a) ?SWAP >R ?SWAP R> ?SWAP ;</syntaxhighlight> |
|||
Testing is done using the Forth console using '?' to view VARIABLE contents |
|||
<pre> ok |
|||
77000 -12 0 VARS! ok |
|||
X ? 77000 ok |
|||
Y ? -12 ok |
|||
Z ? 0 ok |
|||
VARS@ SORT3INTS VARS! ok |
|||
X ? 77000 ok |
|||
Y ? 0 ok |
|||
Z ? -12 ok</PRE> |
|||
==={{header|Strings}}=== |
|||
Strings require extending the language but the primitives needed are part of ANS/ISO Forth. |
|||
<syntaxhighlight lang="forth" lines>DECIMAL |
|||
: BUFFER: ( n -- ) CREATE ALLOT ; |
|||
64 BUFFER: X |
|||
64 BUFFER: Y |
|||
64 BUFFER: Z |
|||
: S' ( <text> ) [CHAR] ' PARSE ; |
|||
S' (from the "Wizard of OZ")' X PLACE |
|||
S' bears, oh my!' Y PLACE |
|||
S' lions, tigers, and' Z PLACE |
|||
\ counted string compare less than |
|||
: <S ( caddr caddr -- caddr caddr flag) |
|||
COUNT ROT COUNT COMPARE 1 = ; |
|||
: ?SWAPSTR ( caddr caddr -- caddr caddr) \ conditional string swap |
|||
2DUP <S IF SWAP THEN ; |
|||
\ sort on stack as done for integers |
|||
: SORT3STRINGS ?SWAPSTR >R ?SWAPSTR R> ?SWAPSTR ; |
|||
\ non-destructive print 3 counted-strings from data stack |
|||
: .STRS ( caddr1 caddr2 caddr3 -- caddr1 caddr2 caddr3) \ order is dependant |
|||
3 0 DO ROT DUP CR COUNT TYPE LOOP ; </syntaxhighlight> |
|||
With these extensions we can do the same testing at the Forth console and |
|||
examine the string order with '.STRS'. |
|||
<PRE> ok |
|||
X Y Z ok |
|||
.S <3> 2142061672 2142061760 2142061848 ok |
|||
.STRS |
|||
(from the "Wizard of OZ") |
|||
bears, oh my! |
|||
lions, tigers, and ok |
|||
SORT3STRINGS ok |
|||
.S <3> 2142061848 2142061760 2142061672 ok |
|||
.STRS |
|||
lions, tigers, and |
|||
bears, oh my! |
|||
(from the "Wizard of OZ") ok</PRE> |
|||
=={{header|Fortran}}== |
=={{header|Fortran}}== |
||
Line 232: | Line 1,336: | ||
There would be similar requirements for a SWAP routine for each type of parameter, for alas, Fortran does not define a SWAP statement. The temporary variable needed for the SWAP process is defined rather intimidatingly as having the size of the largest of the three parameters; prior to F90 variables defined in a routine could only have a size defined at compile time, which would have to be "surely big enough". Rather than have this redefined for each invocation of SWAPC (where it would be the larger of the two parameters) it is defined once in SORT3. However, all three parameters should be the same size, or risk truncation. Using a great deal more syntax (or, as standardised in F2003) it is possible to have character variables be resized on each assignment to them to accommodate the length of text being assigned. |
There would be similar requirements for a SWAP routine for each type of parameter, for alas, Fortran does not define a SWAP statement. The temporary variable needed for the SWAP process is defined rather intimidatingly as having the size of the largest of the three parameters; prior to F90 variables defined in a routine could only have a size defined at compile time, which would have to be "surely big enough". Rather than have this redefined for each invocation of SWAPC (where it would be the larger of the two parameters) it is defined once in SORT3. However, all three parameters should be the same size, or risk truncation. Using a great deal more syntax (or, as standardised in F2003) it is possible to have character variables be resized on each assignment to them to accommodate the length of text being assigned. |
||
One could make rather more use of the facilities of F90 and define a compound data type, such as < |
One could make rather more use of the facilities of F90 and define a compound data type, such as <syntaxhighlight lang="fortran"> TYPE(MONGREL) |
||
INTEGER TYPEIS |
INTEGER TYPEIS |
||
INTEGER VI |
INTEGER VI |
||
Line 239: | Line 1,343: | ||
...etc... |
...etc... |
||
END TYPE MONGREL |
END TYPE MONGREL |
||
TYPE (MONGREL) DOG </ |
TYPE (MONGREL) DOG </syntaxhighlight> |
||
So that DOG.TYPEIS would indicate which component to access. Still further ploys would enable storage to be allocated only for the type currently in use, especially for CHARACTER variables, and via a great deal more syntax defining how to perform operations such as .GT. and the like, MONGREL type variables can be used in expressions involving such operators just as can variables of the basic types. This sort of approach is demonstrated in [[Arithmetic/Rational#Fortran]], but otherwise, every reference to a MONGREL will involve some sort of CASE statement to select the appropriate usage, hopefully of related types only. Serious computation with such MONGREL variables surely will not be speedy and thus would be un-Fortrannish. What to do when a text string meets a complex number remains obscure - convert the number to a text (but, what format?), does the text represent a number? And what type results from such miscegnation? |
So that DOG.TYPEIS would indicate which component to access. Still further ploys would enable storage to be allocated only for the type currently in use, especially for CHARACTER variables, and via a great deal more syntax defining how to perform operations such as .GT. and the like, MONGREL type variables can be used in expressions involving such operators just as can variables of the basic types. This sort of approach is demonstrated in [[Arithmetic/Rational#Fortran]], but otherwise, every reference to a MONGREL will involve some sort of CASE statement to select the appropriate usage, hopefully of related types only. Serious computation with such MONGREL variables surely will not be speedy and thus would be un-Fortrannish. What to do when a text string meets a complex number remains obscure - convert the number to a text (but, what format?), does the text represent a number? And what type results from such miscegnation? |
||
Routines that modify their parameters should not be invoked with constants (or text literals) as such parameters... Some systems allow constants to be in protected storage, and if so, an attempt to modify such storage will produce a run-time error. Otherwise, it all depends on how constants are passed as parameters. If a temporary storage item is loaded with the desired value and the address of that scratch variable is passed, then disaster will be averted - though good results may not be produced. |
Routines that modify their parameters should not be invoked with constants (or text literals) as such parameters... Some systems allow constants to be in protected storage, and if so, an attempt to modify such storage will produce a run-time error. Otherwise, it all depends on how constants are passed as parameters. If a temporary storage item is loaded with the desired value and the address of that scratch variable is passed, then disaster will be averted - though good results may not be produced. |
||
For convenience in setting up the two examples, an array is used to hold the test data. The subroutine is not invoked with an array parameter, it is invoked with three separate elements of the array. The DATA statement initialising the array looks to be the transpose of the desired ordering, because of the way Fortran orders elements in storage. < |
For convenience in setting up the two examples, an array is used to hold the test data. The subroutine is not invoked with an array parameter, it is invoked with three separate elements of the array. The DATA statement initialising the array looks to be the transpose of the desired ordering, because of the way Fortran orders elements in storage. <syntaxhighlight lang="fortran"> SUBROUTINE SORT3(X,Y,Z) !Perpetrate a bubblesort in-line. |
||
CHARACTER*(*) X,Y,Z |
CHARACTER*(*) X,Y,Z !Just three to rearrange. |
||
CHARACTER*(MAX(LEN(X),LEN(Y),LEN(Z))) T |
CHARACTER*(MAX(LEN(X),LEN(Y),LEN(Z))) T !Really, they should all be the same length. |
||
IF (X.GT.Y) CALL SWAPC(X,Y) |
IF (X.GT.Y) CALL SWAPC(X,Y) !The first pass: for i:=2:3 do if a(i - 1) > a(i) swap |
||
IF (Y.GT.Z) CALL SWAPC(Y,Z) |
IF (Y.GT.Z) CALL SWAPC(Y,Z) !The second test of the first pass. |
||
IF (X.GT.Y) CALL SWAPC(X,Y) |
IF (X.GT.Y) CALL SWAPC(X,Y) !The second pass: for i:=2:2... |
||
CONTAINS |
CONTAINS !Alas, Fortran does not offer a SWAP statement. |
||
SUBROUTINE SWAPC(A,B) |
SUBROUTINE SWAPC(A,B) !So, one must be devised for each case. |
||
CHARACTER*(*) A,B |
CHARACTER*(*) A,B !To have their content swapped. |
||
T = A |
T = A !Ccpy the first to a safe space. |
||
A = B |
A = B !Copy the second on to the first. |
||
B = T |
B = T !Copy what had been first to the second. |
||
END SUBROUTINE SWAPC |
END SUBROUTINE SWAPC !One of these will be needed for each type of datum. |
||
END SUBROUTINE SORT3 |
END SUBROUTINE SORT3 !No attempt is made to stop early, as for already-ordered data. |
||
PROGRAM POKE |
PROGRAM POKE |
||
CHARACTER*28 XYZ(3,2) |
CHARACTER*28 XYZ(3,2) !Encompass the two examples. |
||
DATA XYZ/ |
DATA XYZ/ !Storage order is "column-major". |
||
1 'lions, tigers, and','bears, oh my!','(from the "Wizard of OZ")', |
1 'lions, tigers, and','bears, oh my!','(from the "Wizard of OZ")', !So (1,1), (2,1), (3,1) |
||
2 '77444',' -12',' 0'/ |
2 '77444',' -12',' 0'/ !So this looks like a transposed array. But (1,2), (2,2), (3,2) |
||
INTEGER I |
INTEGER I !A stepper for the loop. |
||
DO I = 1,2 |
DO I = 1,2 !Two examples. |
||
WRITE (6,66) "Supplied: ", XYZ(1:3,I) |
WRITE (6,66) "Supplied: ", XYZ(1:3,I) !As given. |
||
66 FORMAT (A12,3(" >",A,"<")) |
66 FORMAT (A12,3(" >",A,"<")) !Show as >text< for clarity. |
||
CALL SORT3(XYZ(1,I),XYZ(2,I),XYZ(3,I)) |
CALL SORT3(XYZ(1,I),XYZ(2,I),XYZ(3,I)) !Three separate variables, that happen to be in an array. |
||
WRITE (6,66) "Sorted, ? ", XYZ(1:3,I) |
WRITE (6,66) "Sorted, ? ", XYZ(1:3,I) !The result. |
||
END DO |
END DO !On to the next example. |
||
END |
END !Nothing much. |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output: the texts showing numbers appear in text order, not the order of their numbers. Incidentally, not everything is done in ASCII. The EBCDIC ordering is different. |
Output: the texts showing numbers appear in text order, not the order of their numbers. Incidentally, not everything is done in ASCII. The EBCDIC ordering is different. |
||
<pre> Supplied: >lions, tigers, and < >bears, oh my! < >(from the "Wizard of OZ") < |
|||
<pre> |
|||
Supplied: >lions, tigers, and < >bears, oh my! < >(from the "Wizard of OZ") < |
|||
Sorted, ? >(from the "Wizard of OZ") < >bears, oh my! < >lions, tigers, and < |
Sorted, ? >(from the "Wizard of OZ") < >bears, oh my! < >lions, tigers, and < |
||
Supplied: >77444 < > -12 < > 0 < |
Supplied: >77444 < > -12 < > 0 < |
||
Sorted, ? > 0 < > -12 < >77444 < |
Sorted, ? > 0 < > -12 < >77444 <</pre> |
||
=={{header|Fōrmulæ}}== |
|||
{{FormulaeEntry|page=https://formulae.org/?script=examples/Sort_three_variables}} |
|||
'''Solution''' |
|||
'''Test case 1''' |
|||
[[File:Fōrmulæ - Sort three variables 01.png]] |
|||
[[File:Fōrmulæ - Sort three variables 02.png]] |
|||
'''Test case 2''' |
|||
[[File:Fōrmulæ - Sort three variables 03.png]] |
|||
[[File:Fōrmulæ - Sort three variables 04.png]] |
|||
=={{header|Free Pascal}}== |
|||
The FPC (FreePascal Compiler) adopted Delphi’s generics scheme. |
|||
It works in the <tt>{$mode objFPC}</tt> and <tt>{$mode Delphi}</tt> compiler compatibility modes, the former requiring the keywords <tt>generic</tt>/<tt>specialize</tt>. |
|||
<syntaxhighlight lang="delphi">{$mode objFPC} |
|||
generic procedure sort<T>(var X, Y: T); |
|||
procedure swap; |
|||
var |
|||
Z: T; |
|||
begin |
|||
Z := X; |
|||
X := Y; |
|||
Y := Z |
|||
end; |
|||
begin |
|||
if X > Y then |
|||
begin |
|||
swap |
|||
end |
|||
end; |
|||
generic procedure sort<T>(var X, Y, Z: T); |
|||
begin |
|||
specialize sort<T>(X, Y); |
|||
specialize sort<T>(X, Z); |
|||
specialize sort<T>(Y, Z) |
|||
end; |
|||
generic procedure print<T>(const X, Y, Z: T); |
|||
begin |
|||
writeLn('X = ', X); |
|||
writeLn('Y = ', Y); |
|||
writeLn('Z = ', Z) |
|||
end; |
|||
{ === MAIN ============================================================= } |
|||
var |
|||
A, B, C: string; |
|||
I, J, K: integer; |
|||
P, Q, R: real; |
|||
begin |
|||
A := 'lions, tigers, and'; |
|||
B := 'bears, oh my!'; |
|||
C := '(from the "Wizard of OZ")'; |
|||
specialize sort<string>(A, B, C); |
|||
specialize print<string>(A, B, C); |
|||
writeLn; |
|||
I := 77444; |
|||
J := -12; |
|||
K := 0; |
|||
specialize sort<integer>(I, J, K); |
|||
specialize print<integer>(I, J, K); |
|||
writeLn; |
|||
P := 12.34; |
|||
Q := -56.78; |
|||
R := 9.01; |
|||
specialize sort<real>(P, Q, R); |
|||
specialize print<real>(P, Q, R) |
|||
end.</syntaxhighlight> |
|||
{{out}} |
|||
<pre>X = (from the "Wizard of OZ") |
|||
Y = bears, oh my! |
|||
Z = lions, tigers, and |
|||
X = -12 |
|||
Y = 0 |
|||
Z = 77444 |
|||
X = -5.6780000000000001E+001 |
|||
Y = 9.0099999999999998E+000 |
|||
Z = 1.2340000000000000E+001</pre> |
|||
=={{header|Frink}}== |
|||
The following sorts the values in the variables x, y, and z and sets the sorted values back to the variables. |
|||
<syntaxhighlight lang="frink">x = 77444 |
|||
y = -12 |
|||
z = 0 |
|||
[x,y,z] = sort[[x,y,z]] |
|||
println["x = $x"] |
|||
println["y = $y"] |
|||
println["z = $z"]</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
x = -12 |
|||
y = 0 |
|||
z = 77444 |
|||
</pre> |
</pre> |
||
=={{header|Go}}== |
=={{header|Go}}== |
||
There are ways of doing this task in a generic way in Go but they are a bit cumbersome and it would not be idiomatic. Shown here then are solutions coded specifically to the string and integer types of the task test cases. Solutions would be very similar for any of the other comparable Go types such as float64. |
There are ways of doing this task in a generic way in Go but they are a bit cumbersome and it would not be idiomatic. Shown here then are solutions coded specifically to the string and integer types of the task test cases. Solutions would be very similar for any of the other comparable Go types such as float64. |
||
< |
<syntaxhighlight lang="go">package main |
||
import ( |
import ( |
||
Line 459: | Line 1,672: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre>sorted strings: |
||
sorted strings: |
|||
(from the "Wizard of OZ") |
(from the "Wizard of OZ") |
||
bears, oh my! |
bears, oh my! |
||
Line 474: | Line 1,686: | ||
</pre> |
</pre> |
||
=={{header| |
=={{header|Haskell}}== |
||
Fortunately, Haskell prevents us from doing this kind of thing. It does makes flexible use of bound names, including names for function arguments, but it also protects us from the heavy costs to productivity and reliability that are inevitably imposed by mutating the meaning of bound names at run-time. |
|||
Note that this is extremely bad form, and you will stumble over why it is bad form if you try using it in any useful implementation: |
|||
Although mutation is not on the menu, parameterised types do allow us to define polymorphic functions which can, for example, be applied both to lists of strings and also to lists of integers or lists of floats. The following functions work with triples of any type for which the '''<=''' or '''compare''' functions are defined – in other words, any type for which an instance of the Ord class is defined. |
|||
<lang J> x =: 'lions, tigers, and' |
|||
<syntaxhighlight lang="haskell">import Data.List (sort) |
|||
sortedTriple |
|||
:: Ord a |
|||
=> (a, a, a) -> (a, a, a) |
|||
sortedTriple (x, y, z) = |
|||
let [a, b, c] = sort [x, y, z] |
|||
in (a, b, c) |
|||
sortedListfromTriple |
|||
:: Ord a |
|||
=> (a, a, a) -> [a] |
|||
sortedListfromTriple (x, y, z) = sort [x, y, z] |
|||
-- TEST ---------------------------------------------------------------------- |
|||
main :: IO () |
|||
main = do |
|||
print $ |
|||
sortedTriple |
|||
("lions, tigers, and", "bears, oh my!", "(from the \"Wizard of OZ\")") |
|||
print $ |
|||
sortedListfromTriple |
|||
("lions, tigers, and", "bears, oh my!", "(from the \"Wizard of OZ\")") |
|||
print $ sortedTriple (77444, -12, 0) |
|||
print $ sortedListfromTriple (77444, -12, 0)</syntaxhighlight> |
|||
{{Out}} |
|||
<pre>("(from the \"Wizard of OZ\")","bears, oh my!","lions, tigers, and") |
|||
["(from the \"Wizard of OZ\")","bears, oh my!","lions, tigers, and"] |
|||
(-12,0,77444) |
|||
[-12,0,77444]</pre> |
|||
=={{header|IS-BASIC}}== |
|||
<syntaxhighlight lang="is-basic">100 LET X=77444:LET Y=-12:LET Z=0 |
|||
110 PRINT X;Y;Z |
|||
120 CALL SHORT(X,Y,Z) |
|||
130 PRINT X;Y;Z |
|||
140 DEF SHORT(REF A,REF B,REF C) |
|||
150 IF A>B THEN LET T=A:LET A=B:LET B=T |
|||
160 IF B>C THEN LET T=B:LET B=C:LET C=T |
|||
170 IF A>B THEN LET T=A:LET A=B:LET B=T |
|||
180 END DEF</syntaxhighlight> |
|||
{{out}} |
|||
<pre> 77444 -12 0 |
|||
-12 0 77444</pre> |
|||
=={{header|J}}== |
|||
Note that this is extremely bad form, and you will stumble over why it is bad form if you try using it in any useful implementation: |
|||
<syntaxhighlight lang="j"> x =: 'lions, tigers, and' |
|||
y =: 'bears, oh my!' |
y =: 'bears, oh my!' |
||
z =: '(from the "Wizard of OZ")' |
z =: '(from the "Wizard of OZ")' |
||
Line 498: | Line 1,759: | ||
0 |
0 |
||
z |
z |
||
77444</ |
77444</syntaxhighlight> |
||
=={{header|Java}}== |
|||
<syntaxhighlight lang="java"> |
|||
import java.util.Comparator; |
|||
import java.util.stream.Stream; |
|||
class Box { |
|||
public int weightKg; |
|||
Box(final int weightKg) { |
|||
this.weightKg = weightKg; |
|||
} |
|||
} |
|||
public class Sort3Vars { |
|||
public static void main(String... args) { |
|||
int iA = 21; |
|||
int iB = 11; |
|||
int iC = 82; |
|||
int[] sortedInt = Stream.of(iA, iB, iC).sorted().mapToInt(Integer::intValue).toArray(); |
|||
iA = sortedInt[0]; |
|||
iB = sortedInt[1]; |
|||
iC = sortedInt[2]; |
|||
System.out.printf("Sorted values: %d %d %d%n", iA, iB, iC); |
|||
String sA = "s21"; |
|||
String sB = "s11"; |
|||
String sC = "s82"; |
|||
Object[] sortedStr = Stream.of(sA, sB, sC).sorted().toArray(); |
|||
sA = (String) sortedStr[0]; |
|||
sB = (String) sortedStr[1]; |
|||
sC = (String) sortedStr[2]; |
|||
System.out.printf("Sorted values: %s %s %s%n", sA, sB, sC); |
|||
Box bA = new Box(200); |
|||
Box bB = new Box(12); |
|||
Box bC = new Box(143); |
|||
// Provides a comparator for Box instances |
|||
Object[] sortedBox = Stream.of(bA, bB, bC).sorted(Comparator.comparingInt(a -> a.weightKg)).toArray(); |
|||
bA = (Box) sortedBox[0]; |
|||
bB = (Box) sortedBox[1]; |
|||
bC = (Box) sortedBox[2]; |
|||
System.out.printf("Sorted Boxes: %dKg %dKg %dKg%n", bA.weightKg, bB.weightKg, bC.weightKg); |
|||
} |
|||
} |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre>Sorted values: 11 21 82 |
|||
Sorted values: s11 s21 s82 |
|||
Sorted Boxes: 12Kg 143Kg 200Kg</pre> |
|||
=={{header|JavaScript}}== |
|||
<syntaxhighlight lang="javascript">const printThree = (note, [a, b, c], [a1, b1, c1]) => { |
|||
console.log(`${note} |
|||
${a} is: ${a1} |
|||
${b} is: ${b1} |
|||
${c} is: ${c1} |
|||
`); |
|||
}; |
|||
const sortThree = () => { |
|||
let a = 'lions, tigers, and'; |
|||
let b = 'bears, oh my!'; |
|||
let c = '(from the "Wizard of OZ")'; |
|||
printThree('Before Sorting', ['a', 'b', 'c'], [a, b, c]); |
|||
[a, b, c] = [a, b, c].sort(); |
|||
printThree('After Sorting', ['a', 'b', 'c'], [a, b, c]); |
|||
let x = 77444; |
|||
let y = -12; |
|||
let z = 0; |
|||
printThree('Before Sorting', ['x', 'y', 'z'], [x, y, z]); |
|||
[x, y, z] = [x, y, z].sort(); |
|||
printThree('After Sorting', ['x', 'y', 'z'], [x, y, z]); |
|||
}; |
|||
sortThree(); |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre>Before Sorting |
|||
a is: lions, tigers, and |
|||
b is: bears, oh my! |
|||
c is: (from the "Wizard of OZ") |
|||
After Sorting |
|||
a is: (from the "Wizard of OZ") |
|||
b is: bears, oh my! |
|||
c is: lions, tigers, and |
|||
Before Sorting |
|||
x is: 77444 |
|||
y is: -12 |
|||
z is: 0 |
|||
After Sorting |
|||
x is: -12 |
|||
y is: 0 |
|||
z is: 77444 |
|||
</pre> |
|||
=={{header|jq}}== |
|||
In this entry, we shall use a JSON object to represent a set of variables and their bindings. jq supports this interpretation: for example, the assignment operator '=' can be used to set the value associated with a key, as in `.x = 0`. |
|||
jq also allows JSON objects to be specified in a jq program using a JSON-like syntax, e.g. {x: 1}, as illustrated below. |
|||
The sorting function defined here is completely generic with respect to the number of variables and the types of their values. For brevity, however, we will only use the required examples. |
|||
<syntaxhighlight lang="jq">def example1: |
|||
{x: "lions, tigers, and", |
|||
y: "bears, oh my", |
|||
z: "(from the \"Wizard of OZ\")" |
|||
}; |
|||
def example2: |
|||
{x: 77444, |
|||
y: -12, |
|||
z: 0 |
|||
};</syntaxhighlight> |
|||
The following sorting function will accept an arbitrary JSON object: |
|||
<syntaxhighlight lang="text">def sortVariables: |
|||
keys_unsorted as $keys |
|||
| ([.[]] | sort) as $values |
|||
| reduce range(0; $keys|length) as $i ({}; .[$keys[$i]] = ($values[$i]) ) ;</syntaxhighlight> |
|||
Examples: |
|||
<syntaxhighlight lang="jq">example1 | sortVariables</syntaxhighlight> |
|||
{{out}} |
|||
<pre>{ |
|||
"x": "(from the \"Wizard of OZ\")", |
|||
"y": "bears, oh my", |
|||
"z": "lions, tigers, and" |
|||
} |
|||
</pre> |
|||
<syntaxhighlight lang="jq">example2 | sortVariables</syntaxhighlight> |
|||
{{out}}<pre> |
|||
{ |
|||
"x": -12, |
|||
"y": 0, |
|||
"z": 77444 |
|||
}</pre> |
|||
=={{header|Jsish}}== |
|||
<syntaxhighlight lang="javascript">#!/usr/bin/env jsish |
|||
/* Sort three variables, in Jsish. semi-colon start/end for unit test echo */ |
|||
var x = 'lions, tigers, and'; |
|||
var y = 'bears, oh my!'; |
|||
var z = '(from the "Wizard of OZ")'; |
|||
var arr = [x,y,z]; |
|||
arr = arr.sort(); |
|||
;'As strings, before:'; |
|||
;x; |
|||
;y; |
|||
;z; |
|||
x = arr.shift(); |
|||
y = arr.shift(); |
|||
z = arr.shift(); |
|||
;'x,y,z after:'; |
|||
;x; |
|||
;y; |
|||
;z; |
|||
x = 77444; |
|||
y = -12; |
|||
z = 0; |
|||
arr = [x,y,z]; |
|||
arr = arr.sort(); |
|||
;'As numbers before:'; |
|||
;x; |
|||
;y; |
|||
;z; |
|||
x = arr.shift(); |
|||
y = arr.shift(); |
|||
z = arr.shift(); |
|||
;'x,y,z after:'; |
|||
;x; |
|||
;y; |
|||
;z; |
|||
;'Mixed, integer, float, string'; |
|||
x = 3.14159; |
|||
y = 2; |
|||
z = '1 string'; |
|||
;x; |
|||
;y; |
|||
;z; |
|||
arr = [x,y,z].sort(); |
|||
x = arr.shift(); y = arr.shift(); z = arr.shift(); |
|||
;'x,y,z after:'; |
|||
;x; |
|||
;y; |
|||
;z; |
|||
/* |
|||
=!EXPECTSTART!= |
|||
'As strings, before:' |
|||
x ==> lions, tigers, and |
|||
y ==> bears, oh my! |
|||
z ==> (from the "Wizard of OZ") |
|||
'x,y,z after:' |
|||
x ==> (from the "Wizard of OZ") |
|||
y ==> bears, oh my! |
|||
z ==> lions, tigers, and |
|||
'As numbers before:' |
|||
x ==> 77444 |
|||
y ==> -12 |
|||
z ==> 0 |
|||
'x,y,z after:' |
|||
x ==> -12 |
|||
y ==> 0 |
|||
z ==> 77444 |
|||
'Mixed, integer, float, string' |
|||
x ==> 3.14159 |
|||
y ==> 2 |
|||
z ==> 1 string |
|||
'x,y,z after:' |
|||
x ==> 2 |
|||
y ==> 3.14159 |
|||
z ==> 1 string |
|||
=!EXPECTEND!= |
|||
*/</syntaxhighlight> |
|||
{{out}} |
|||
<pre>prompt$ jsish --U sortThree.jsi |
|||
'As strings, before:' |
|||
x ==> lions, tigers, and |
|||
y ==> bears, oh my! |
|||
z ==> (from the "Wizard of OZ") |
|||
'x,y,z after:' |
|||
x ==> (from the "Wizard of OZ") |
|||
y ==> bears, oh my! |
|||
z ==> lions, tigers, and |
|||
'As numbers before:' |
|||
x ==> 77444 |
|||
y ==> -12 |
|||
z ==> 0 |
|||
'x,y,z after:' |
|||
x ==> -12 |
|||
y ==> 0 |
|||
z ==> 77444 |
|||
'Mixed, integer, float, string' |
|||
x ==> 3.14159 |
|||
y ==> 2 |
|||
z ==> 1 string |
|||
'x,y,z after:' |
|||
x ==> 2 |
|||
y ==> 3.14159 |
|||
z ==> 1 string |
|||
prompt$ jsish -u sortThree.jsi |
|||
[PASS] sortThree.jsi</pre> |
|||
=={{header|Julia}}== |
|||
<syntaxhighlight lang="julia"># v0.6 |
|||
a, b, c = "lions, tigers, and", "bears, oh my!", "(from the \"Wizard of OZ\")" |
|||
a, b, c = sort([a, b, c]) |
|||
@show a b c |
|||
a, b, c = 77444, -12, 0 |
|||
a, b, c = sort([a, b, c]) |
|||
@show a b c</syntaxhighlight> |
|||
{{out}} |
|||
<pre>a = "(from the \"Wizard of OZ\")" |
|||
b = "bears, oh my!" |
|||
c = "lions, tigers, and" |
|||
a = -12 |
|||
b = 0 |
|||
c = 77444</pre> |
|||
=={{header|Kotlin}}== |
=={{header|Kotlin}}== |
||
Kotlin's standard library contains a sort() function which can sort any generic array whose element type has a defined ordering between its instances. This includes strings, integers and floats examples of which are shown below: |
Kotlin's standard library contains a sort() function which can sort any generic array whose element type has a defined ordering between its instances. This includes strings, integers and floats examples of which are shown below: |
||
< |
<syntaxhighlight lang="scala">// version 1.1.2 |
||
inline fun <reified T : Comparable<T>> sortThree(x: T, y: T, z: T): Triple<T, T, T> { |
inline fun <reified T : Comparable<T>> sortThree(x: T, y: T, z: T): Triple<T, T, T> { |
||
Line 539: | Line 2,080: | ||
z3 = t3.third |
z3 = t3.third |
||
printThree(x3, y3, z3) |
printThree(x3, y3, z3) |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>x = (from the "Wizard of OZ") |
|||
<pre> |
|||
x = (from the "Wizard of OZ") |
|||
y = bears, oh my! |
y = bears, oh my! |
||
z = lions, tigers, and |
z = lions, tigers, and |
||
Line 553: | Line 2,093: | ||
x = -62.5 |
x = -62.5 |
||
y = 41.7 |
y = 41.7 |
||
z = 174.5 |
z = 174.5</pre> |
||
=={{header|Ksh}}== |
|||
<syntaxhighlight lang="ksh"> |
|||
#!/bin/ksh |
|||
# Sort three variables that may contain any value (numbers and/or literals) |
|||
# # Variables: |
|||
# |
|||
xl='lions, tigers, and' |
|||
yl='bears, oh my!' |
|||
zl='(from the "Wizard of OZ")' |
|||
typeset -i xn=77444 |
|||
typeset -F yn=-12.0 |
|||
typeset -i zn=0 |
|||
# # Functions: |
|||
# |
|||
# # Function _intoarray(x, y, z, arr) - put 3 variables into arr[] |
|||
# |
|||
function _intoarray { |
|||
typeset _x ; nameref _x="$1" |
|||
typeset _y ; nameref _y="$2" |
|||
typeset _z ; nameref _z="$3" |
|||
typeset _arr ; nameref _arr="$4" |
|||
_arr=( "${_x}" "${_y}" "${_z}" ) |
|||
} |
|||
# # Function _arraysort(arr) - return sorted array (any type of elements) |
|||
# |
|||
function _arraysort { |
|||
typeset _arr ; nameref _arr="$1" |
|||
typeset _i _j ; integer _i _j |
|||
_sorttype _arr |
|||
case $? in |
|||
0) # Literal sort |
|||
for (( _i=1; _i<${#_arr[*]}; _i++ )); do |
|||
_val="${_arr[_i]}" |
|||
(( _j = _i - 1 )) |
|||
while (( _j>=0 )) && [[ "${_arr[_j]}" > "${_val}" ]]; do |
|||
_arr[_j+1]="${_arr[_j]}" |
|||
(( _j-- )) |
|||
done |
|||
_arr[_j+1]="${_val}" |
|||
done |
|||
;; |
|||
1) # Numeric sort |
|||
for (( _i=1; _i<${#_arr[*]}; _i++ )); do |
|||
_val=${_arr[_i]} |
|||
(( _j = _i - 1 )) |
|||
while (( _j>=0 && _arr[_j]>_val )); do |
|||
_arr[_j+1]=${_arr[_j]} |
|||
(( _j-- )) |
|||
done |
|||
_arr[_j+1]=${_val} |
|||
done |
|||
;; |
|||
esac |
|||
} |
|||
# # Function _sorttype(_arr) - return 0 = Literal sort; 1 = Numeric sort |
|||
# |
|||
function _sorttype { |
|||
typeset _arr ; nameref _arr="$1" |
|||
typeset _i ; integer _i |
|||
for ((_i=0; _i<${#_arr[*]}; _i++)); do |
|||
[[ ${_arr[_i]} != *(\-)+(\d)*(\.)*(\d) ]] && return 0 |
|||
done |
|||
return 1 |
|||
} |
|||
# # Function _outofarray(x, y, z, arr) - Put array elements into x, y, z |
|||
# |
|||
function _outofarray { |
|||
typeset _x ; nameref _x="$1" |
|||
typeset _y ; nameref _y="$2" |
|||
typeset _z ; nameref _z="$3" |
|||
typeset _arr ; nameref _arr="$4" |
|||
_x="${_arr[0]}" |
|||
_y="${_arr[1]}" |
|||
_z="${_arr[2]}" |
|||
} |
|||
###### |
|||
# main # |
|||
###### |
|||
unset x y z |
|||
printf "Numeric Variables:\n%s\n%s\n%s\n\n" "${xn}" "${yn}" "${zn}" |
|||
typeset -a arrayn |
|||
_intoarray xn yn zn arrayn |
|||
_arraysort arrayn |
|||
_outofarray x y z arrayn |
|||
printf "Sorted Variables:\n%s\n%s\n%s\n\n" "${x}" "${y}" "${z}" |
|||
unset x y z |
|||
printf "Literal Variables:\n%s\n%s\n%s\n\n" "${xl}" "${yl}" "${zl}" |
|||
typeset -a arrayl |
|||
_intoarray xl yl zl arrayl |
|||
_arraysort arrayl |
|||
_outofarray x y z arrayl |
|||
printf "Sorted Variables:\n%s\n%s\n%s\n\n" "${x}" "${y}" "${z}"</syntaxhighlight> |
|||
{{out}}<pre> |
|||
Numeric Variables: |
|||
77444 |
|||
-12.0000000000000 |
|||
0 |
|||
Sorted Variables: |
|||
-12.0000000000000 |
|||
0 |
|||
77444 |
|||
Literal Variables: |
|||
lions, tigers, and |
|||
bears, oh my! |
|||
(from the "Wizard of OZ") |
|||
Sorted Variables: |
|||
bears, oh my! |
|||
(from the "Wizard of OZ") |
|||
lions, tigers, and</pre> |
|||
=={{header|Little Man Computer}}== |
|||
The LMC in its original form supports only integers in the range 0..999. So the numbers in the task have been changed here from 77444, -12, 0 to 774, 0, 12. |
|||
<syntaxhighlight lang="little man computer"> |
|||
// Little Man Computer |
|||
// Sort x, y, z, in ascending order |
|||
// Based on a sorting network: |
|||
// if x > z then swap( x, z) |
|||
// if x > y then swap( x, y) |
|||
// if y > z then swap( y, z) |
|||
// with the addition that if the 2nd swap is executed |
|||
// then the 3rd comparison is not needed. |
|||
// Read numbers x, y, z, and display in their original order |
|||
INP |
|||
STA x |
|||
OUT |
|||
INP |
|||
STA y |
|||
OUT |
|||
INP |
|||
STA z |
|||
OUT |
|||
// Sort so that x <= y <= z, and display in new order |
|||
LDA z |
|||
SUB x |
|||
BRP label1 |
|||
LDA x |
|||
STA t |
|||
LDA z |
|||
STA x |
|||
LDA t |
|||
STA z |
|||
label1 LDA y |
|||
SUB x |
|||
BRP label2 |
|||
LDA x |
|||
STA t |
|||
LDA y |
|||
STA x |
|||
LDA t |
|||
STA y |
|||
BRA sorted // added to the sorting network |
|||
label2 LDA z |
|||
SUB y |
|||
BRP sorted |
|||
LDA y |
|||
STA t |
|||
LDA z |
|||
STA y |
|||
LDA t |
|||
STA z |
|||
sorted LDA x |
|||
OUT |
|||
LDA y |
|||
OUT |
|||
LDA z |
|||
OUT |
|||
HLT |
|||
x DAT |
|||
y DAT |
|||
z DAT |
|||
t DAT |
|||
// end |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
744 |
|||
0 |
|||
12 |
|||
0 |
|||
12 |
|||
744 |
|||
</pre> |
</pre> |
||
=={{header|Lua}}== |
=={{header|Lua}}== |
||
Essentially the same as the example algorithm except that the function is variadic. Sorting is done by the in-built table.sort and copying the unknown number of variables in and out of the table is made simple by the (...) in the parameter list and the unpack function respectively. |
Essentially the same as the example algorithm except that the function is variadic. Sorting is done by the in-built table.sort and copying the unknown number of variables in and out of the table is made simple by the (...) in the parameter list and the unpack function respectively. |
||
< |
<syntaxhighlight lang="lua">function variadicSort (...) |
||
local t = {} |
local t = {} |
||
for _, x in pairs{...} do |
for _, x in pairs{...} do |
||
Line 583: | Line 2,326: | ||
print("\ty = " .. y) |
print("\ty = " .. y) |
||
print("\tz = " .. z) |
print("\tz = " .. z) |
||
end</ |
end</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>Case 1 |
<pre>Case 1 |
||
Line 594: | Line 2,337: | ||
y = 0 |
y = 0 |
||
z = 77444</pre> |
z = 77444</pre> |
||
=={{header|M2000 Interpreter}}== |
|||
Variables in M2000 are type of Variant, Interpreter use name type ($) to use proper expression parser something as string. |
|||
In this example we pass reference from numeric to string identifiers, but data under never moved, so we can read the type, and then |
|||
we can make second reference to numeric names, and then we use the proper expression parser. |
|||
Swap statement swap variants (data), not references, and always swap 16bytes. All arrays are variant type, so we can swap array item with any variable (but names must be the same type - strings or numeric both) |
|||
Subs can be found from parent context, but executed like they are in current context. A sub has scope in Module, so can call any sub including itself. For optimization , Interpreter mark in temporary list the sub positions, at the first call. |
|||
Modules and Functions have a special list, where included at definition time, end excluded when parent exit. |
|||
<syntaxhighlight lang="m2000 interpreter"> |
|||
Module Sort3 { |
|||
Let X=77744, Y=-12, Z=0 |
|||
Let X$ = "lions, tigers, and", Y$ = "bears, oh my!", Z$ = {(from the "Wizard of OZ")} |
|||
\\ & use for by reference pass |
|||
Module SortSome (&X$, &Y$, &Z$){ |
|||
If Type$(X$)<>"String" Then { |
|||
Link X$,Y$, Z$ to X,Y,Z |
|||
Print3() |
|||
If Y>Z then Swap Y, Z ' both numeric in Swap |
|||
If X>Z then Swap X, Z |
|||
If X>Y then Swap X, Y |
|||
Print3() |
|||
} Else { |
|||
Print3Str() |
|||
If Y$>Z$ then Swap Y$, Z$ ' both strings in Swap |
|||
If X$>Z$ then Swap X$, Z$ |
|||
If X$>Y$ then Swap X$, Y$ |
|||
Print3Str() |
|||
} |
|||
} |
|||
SortSome &X, &Y, &Z |
|||
SortSome &X$, &Y$, &Z$ |
|||
Sub Print3() |
|||
\\ double ,, used to insert a New Line |
|||
Print "X=",X,,"Y=",Y,,"Z=",Z |
|||
End Sub |
|||
Sub Print3Str() |
|||
Print "X$=",X$,,"Y$=",Y$,,"Z$=",Z$ |
|||
End Sub |
|||
} |
|||
Sort3 |
|||
</syntaxhighlight> |
|||
=={{header|Maple}}== |
|||
<syntaxhighlight lang="maple">lst := sort([x,y,z]): |
|||
x,y,z := lst[1],lst[2],lst[3]:</syntaxhighlight> |
|||
{{Out|Example}} |
|||
x := 'lions, tigers, and': |
|||
y := 'bears, oh my!': |
|||
z := '(from the "Wizard of OZ")': |
|||
<pre>>>>x; |
|||
"(from the "Wizard of OZ")" |
|||
>>>y; |
|||
"bears, oh my!" |
|||
>>>z; |
|||
"lions, tigers, and"</pre> |
|||
x := 77444: |
|||
y := -12: |
|||
z := 0: |
|||
<pre>>>>x; |
|||
-12 |
|||
>>>y; |
|||
0 |
|||
>>>z; |
|||
77444</pre> |
|||
=={{header|Mathematica}}/{{header|Wolfram Language}}== |
|||
All variables in Mathematica are typeless so the follow code works in all cases |
|||
<syntaxhighlight lang="mathematica">{x, y, z} = Sort[{x, y, z}]</syntaxhighlight> |
|||
example: |
|||
<syntaxhighlight lang="mathematica">x = 77444; |
|||
y = -12; |
|||
z = 0; |
|||
{x, y, z} = Sort[{x, y, z}]; |
|||
{x, y, z}</syntaxhighlight> |
|||
{{out}} |
|||
<pre>{-12, 0, 77444}</pre> |
|||
=={{header|min}}== |
|||
{{works with|min|0.19.3}} |
|||
The <code>sort3</code> operator updates the values of the variables given to it in the calling scope, much like passing by reference. A small drawback is that we must quote the symbols passed in, lest we lose access to them. |
|||
<syntaxhighlight lang="min">(=c =b =a (a -> b -> c ->) => '> sort -> c @ b @ a @) :sort3 |
|||
"lions, tigers, and" :x |
|||
"bears, oh my!" :y |
|||
"(from the \"Wizard of OZ\")" :z |
|||
'x 'y 'z sort3 |
|||
x puts! |
|||
y puts! |
|||
z puts! |
|||
77444 :x |
|||
-12 :y |
|||
0 :z |
|||
'x 'y 'z sort3 |
|||
x puts! |
|||
y puts! |
|||
z puts!</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
(from the "Wizard of OZ") |
|||
bears, oh my! |
|||
lions, tigers, and |
|||
-12 |
|||
0 |
|||
77444 |
|||
</pre> |
|||
=={{header|Modula-2}}== |
|||
{{Output?}} |
|||
<syntaxhighlight lang="modula2">MODULE SortThreeVariables; |
|||
FROM FormatString IMPORT FormatString; |
|||
FROM Terminal IMPORT WriteString,WriteLn,ReadChar; |
|||
PROCEDURE SwapInt(VAR a,b : INTEGER); |
|||
VAR t : INTEGER; |
|||
BEGIN |
|||
t := a; |
|||
a := b; |
|||
b := t; |
|||
END SwapInt; |
|||
PROCEDURE Sort3Int(VAR x,y,z : INTEGER); |
|||
BEGIN |
|||
IF x<y THEN |
|||
IF z<x THEN |
|||
SwapInt(x,z); |
|||
END; |
|||
ELSIF y<z THEN |
|||
SwapInt(x,y); |
|||
ELSE |
|||
SwapInt(x,z); |
|||
END; |
|||
IF z<y THEN |
|||
SwapInt(y,z); |
|||
END; |
|||
END Sort3Int; |
|||
VAR |
|||
buf : ARRAY[0..63] OF CHAR; |
|||
a,b,c : INTEGER; |
|||
BEGIN |
|||
a := 77444; |
|||
b := -12; |
|||
c := 0; |
|||
FormatString("Before a=[%i]; b=[%i]; c=[%i]\n", buf, a, b, c); |
|||
WriteString(buf); |
|||
Sort3Int(a,b,c); |
|||
FormatString("Before a=[%i]; b=[%i]; c=[%i]\n", buf, a, b, c); |
|||
WriteString(buf); |
|||
ReadChar; |
|||
END SortThreeVariables.</syntaxhighlight> |
|||
=={{header|Nanoquery}}== |
|||
<syntaxhighlight lang="nanoquery">import sort |
|||
// sorting string literals |
|||
x = "lion, tigers, and" |
|||
y = "bears, oh my!" |
|||
z = "(from the \"Wizard of OZ\")" |
|||
varlist = sort({x,y,z}) |
|||
x = varlist[0] |
|||
y = varlist[1] |
|||
z = varlist[2] |
|||
println x; println y; println z |
|||
// sorting integers |
|||
x = 77444 |
|||
y = -12 |
|||
z = 0 |
|||
varlist = sort({x, y, z}) |
|||
x = varlist[0] |
|||
y = varlist[1] |
|||
z = varlist[2] |
|||
println x; println y; println z</syntaxhighlight> |
|||
{{out}} |
|||
<pre>(from the "Wizard of OZ") |
|||
bears, oh my! |
|||
lion, tigers, and |
|||
-12 |
|||
0 |
|||
77444</pre> |
|||
=={{header|Nim}}== |
|||
<syntaxhighlight lang="nim">proc sortThree[T](a, b, c: var T) = |
|||
# Bubble sort, why not? |
|||
while not (a <= b and b <= c): |
|||
if a > b: swap a, b |
|||
if b > c: swap b, c |
|||
proc testWith[T](a, b, c: T) = |
|||
var (x, y, z) = (a, b, c) |
|||
echo "Before: ", x, ", ", y, ", ", z |
|||
sortThree(x, y, z) |
|||
echo "After: ", x, ", ", y, ", ", z |
|||
testWith(6, 4, 2) |
|||
testWith(0.9, -37.1, 4.0) |
|||
testWith("lions", "tigers", "bears")</syntaxhighlight> |
|||
{{out}} |
|||
<pre>Before: 6, 4, 2 |
|||
After: 2, 4, 6 |
|||
Before: 0.9, -37.1, 4.0 |
|||
After: -37.1, 0.9, 4.0 |
|||
Before: lions, tigers, bears |
|||
After: bears, lions, tigers</pre> |
|||
=={{header|OCaml}}== |
|||
<syntaxhighlight lang="ocaml">let sortrefs list = |
|||
let sorted = List.map ( ! ) list |
|||
|> List.sort (fun a b -> |
|||
if a < b then -1 else |
|||
if a > b then 1 else |
|||
0) in |
|||
List.iter2 (fun v x -> v := x) list sorted |
|||
open Printf |
|||
let test () = |
|||
let x = ref "lions, tigers, and" in |
|||
let y = ref "bears, oh my!" in |
|||
let z = ref "(from the \"Wizard of OZ\")" in |
|||
sortrefs [x; y; z]; |
|||
print_endline "case 1:"; |
|||
printf "\tx: %s\n" !x; |
|||
printf "\ty: %s\n" !y; |
|||
printf "\tz: %s\n" !z; |
|||
let x = ref 77444 in |
|||
let y = ref (-12) in |
|||
let z = ref 0 in |
|||
sortrefs [x; y; z]; |
|||
print_endline "case 1:"; |
|||
printf "\tx: %d\n" !x; |
|||
printf "\ty: %d\n" !y; |
|||
printf "\tz: %d\n" !z</syntaxhighlight> |
|||
{{out}} |
|||
<pre># test ();; |
|||
case 1: |
|||
x: (from the "Wizard of OZ") |
|||
y: bears, oh my! |
|||
z: lions, tigers, and |
|||
case 1: |
|||
x: -12 |
|||
y: 0 |
|||
z: 77444 |
|||
- : unit = ()</pre> |
|||
=={{header|Pascal}}== |
|||
{{works with|Extended Pascal}} |
|||
Pascal is a statically typed programming language. |
|||
The data types of all variables and routine parameters need to be known in advance. |
|||
The following <tt>program</tt> demonstrates sorting three strings, but can be easily adapted to work for <tt>integer</tt> and <tt>real</tt> variables as well. |
|||
<syntaxhighlight lang="pascal">program sortThreeVariables(output); |
|||
type |
|||
{ this Extended Pascal data type may hold up to 25 `char` values } |
|||
line = string(25); |
|||
{ this procedure sorts two lines } |
|||
procedure sortLines(var X, Y: line); |
|||
{ nested procedure allocates space for Z only if needed } |
|||
procedure swap; |
|||
var |
|||
Z: line; |
|||
begin |
|||
Z := X; |
|||
X := Y; |
|||
Y := Z |
|||
end; |
|||
begin |
|||
{ for lexical sorting write `if GT(X, Y) then` } |
|||
if X > Y then |
|||
begin |
|||
swap |
|||
end |
|||
end; |
|||
{ sorts three line variables’s values } |
|||
procedure sortThreeLines(var X, Y, Z: line); |
|||
begin |
|||
{ `var` parameters can be modified at the calling site } |
|||
sortLines(X, Y); |
|||
sortLines(X, Z); |
|||
sortLines(Y, Z) |
|||
end; |
|||
{ writes given lines on output preceded by `X = `, `Y = ` and `Z = ` } |
|||
procedure printThreeLines(protected X, Y, Z: line); |
|||
begin |
|||
{ `protected` parameters cannot be overwritten } |
|||
writeLn('X = ', X); |
|||
writeLn('Y = ', Y); |
|||
writeLn('Z = ', Z) |
|||
end; |
|||
{ === MAIN ============================================================= } |
|||
var |
|||
A, B: line; |
|||
{ for demonstration purposes: alternative method to initialize } |
|||
C: line value '(from the "Wizard of OZ")'; |
|||
begin |
|||
A := 'lions, tigers, and'; |
|||
B := 'bears, oh my!'; |
|||
sortThreeLines(A, B, C); |
|||
printThreeLines(A, B, C) |
|||
end.</syntaxhighlight> |
|||
=={{header|Perl}}== |
=={{header|Perl}}== |
||
Line 599: | Line 2,662: | ||
{{works with|Perl|5.10+}} |
{{works with|Perl|5.10+}} |
||
< |
<syntaxhighlight lang="perl">#!/usr/bin/env perl |
||
use 5.010_000; |
use 5.010_000; |
||
Line 611: | Line 2,674: | ||
( $x, $y, $z ) = sort ( $x, $y, $z ); |
( $x, $y, $z ) = sort ( $x, $y, $z ); |
||
say 'Case 1:' |
say 'Case 1:'; |
||
say " x = $x"; |
say " x = $x"; |
||
say " y = $y"; |
say " y = $y"; |
||
Line 626: | Line 2,689: | ||
( $x, $y, $z ) = sort { $a <=> $b } ( $x, $y, $z ); |
( $x, $y, $z ) = sort { $a <=> $b } ( $x, $y, $z ); |
||
say 'Case 2:' |
say 'Case 2:'; |
||
say " x = $x"; |
say " x = $x"; |
||
say " y = $y"; |
say " y = $y"; |
||
say " z = $z";</ |
say " z = $z";</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 642: | Line 2,705: | ||
z = 77444</pre> |
z = 77444</pre> |
||
=={{header| |
=={{header|Phix}}== |
||
Phix is naturally polymorphic |
|||
Perl 6 has a built in sort routine which uses a variation of quicksort. The built in sort routine will automatically select a numeric sort if given a list of Real numeric items and a lexical Unicode sort if given a list that contains strings. The default numeric sort won't sort complex numbers unless you give it a custom comparitor. It is trivial to modify the sort comparitor function to get whatever ordering you want though. |
|||
<!--<syntaxhighlight lang="phix">(phixonline)--> |
|||
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span> |
|||
<span style="color: #004080;">object</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">x</span><span style="color: #0000FF;">,</span><span style="color: #000000;">y</span><span style="color: #0000FF;">,</span><span style="color: #000000;">z</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #008000;">"lions, tigers, and"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"bears, oh my"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"(from the \"Wizard of OZ\")"</span><span style="color: #0000FF;">}</span> |
|||
<span style="color: #0000FF;">?{</span><span style="color: #000000;">x</span><span style="color: #0000FF;">,</span><span style="color: #000000;">y</span><span style="color: #0000FF;">,</span><span style="color: #000000;">z</span><span style="color: #0000FF;">}</span> |
|||
<span style="color: #0000FF;">{</span><span style="color: #000000;">x</span><span style="color: #0000FF;">,</span><span style="color: #000000;">y</span><span style="color: #0000FF;">,</span><span style="color: #000000;">z</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">sort</span><span style="color: #0000FF;">({</span><span style="color: #000000;">x</span><span style="color: #0000FF;">,</span><span style="color: #000000;">y</span><span style="color: #0000FF;">,</span><span style="color: #000000;">z</span><span style="color: #0000FF;">})</span> <span style="color: #0000FF;">?{</span><span style="color: #000000;">x</span><span style="color: #0000FF;">,</span><span style="color: #000000;">y</span><span style="color: #0000FF;">,</span><span style="color: #000000;">z</span><span style="color: #0000FF;">}</span> |
|||
<span style="color: #0000FF;">{</span><span style="color: #000000;">x</span><span style="color: #0000FF;">,</span><span style="color: #000000;">y</span><span style="color: #0000FF;">,</span><span style="color: #000000;">z</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">77444</span><span style="color: #0000FF;">,-</span><span style="color: #000000;">12</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">?{</span><span style="color: #000000;">x</span><span style="color: #0000FF;">,</span><span style="color: #000000;">y</span><span style="color: #0000FF;">,</span><span style="color: #000000;">z</span><span style="color: #0000FF;">}</span> |
|||
<span style="color: #0000FF;">{</span><span style="color: #000000;">x</span><span style="color: #0000FF;">,</span><span style="color: #000000;">y</span><span style="color: #0000FF;">,</span><span style="color: #000000;">z</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">sort</span><span style="color: #0000FF;">({</span><span style="color: #000000;">x</span><span style="color: #0000FF;">,</span><span style="color: #000000;">y</span><span style="color: #0000FF;">,</span><span style="color: #000000;">z</span><span style="color: #0000FF;">})</span> <span style="color: #0000FF;">?{</span><span style="color: #000000;">x</span><span style="color: #0000FF;">,</span><span style="color: #000000;">y</span><span style="color: #0000FF;">,</span><span style="color: #000000;">z</span><span style="color: #0000FF;">}</span> |
|||
<!--</syntaxhighlight>--> |
|||
{{out}} |
|||
<pre>{"lions, tigers, and","bears, oh my","(from the \"Wizard of OZ\")"} |
|||
{"(from the \"Wizard of OZ\")","bears, oh my","lions, tigers, and"} |
|||
{77444,-12,0} |
|||
{-12,0,77444}</pre> |
|||
=={{header|PHP}}== |
|||
<syntaxhighlight lang="php"><?php |
|||
//Sort strings |
|||
$x = 'lions, tigers, and'; |
|||
$y = 'bears, oh my!'; |
|||
$z = '(from the "Wizard of OZ")'; |
|||
$items = [$x, $y, $z]; |
|||
sort($items); |
|||
list($x, $y, $z) = $items; |
|||
echo <<<EOT |
|||
Case 1: |
|||
x = $x |
|||
y = $y |
|||
z = $z |
|||
EOT; |
|||
//Sort numbers |
|||
$x = 77444; |
|||
$y = -12; |
|||
$z = 0; |
|||
$items = [$x, $y, $z]; |
|||
sort($items); |
|||
list($x, $y, $z) = $items; |
|||
echo <<<EOT |
|||
Case 2: |
|||
x = $x |
|||
y = $y |
|||
z = $z |
|||
EOT; |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre>Case 1: |
|||
x = (from the "Wizard of OZ") |
|||
y = bears, oh my! |
|||
z = lions, tigers, and |
|||
Case 2: |
|||
x = -12 |
|||
y = 0 |
|||
z = 77444 |
|||
</pre> |
|||
=={{header|PicoLisp}}== |
|||
<syntaxhighlight lang="picolisp">(let (X 77444 Y -12 Z 0) |
|||
(println X Y Z) |
|||
(mapc set '(X Y Z) (sort (list X Y Z))) |
|||
(println X Y Z) )</syntaxhighlight> |
|||
{{out}} |
|||
<pre>77444 -12 0 |
|||
-12 0 77444</pre> |
|||
=={{header|Plain English}}== |
|||
This will sort integers only. |
|||
<syntaxhighlight lang="plainenglish">To run: |
|||
Start up. |
|||
Sort three numbers. |
|||
Wait for the escape key. |
|||
Shut down. |
|||
To sort three numbers: |
|||
Put 77444 into an x number. |
|||
Put -12 into a y number. |
|||
Put 0 into a z number. |
|||
Write "===Before sorting===" on the console. |
|||
Write "x: " then the x on the console. |
|||
Write "y: " then the y on the console. |
|||
Write "z: " then the z on the console. |
|||
Sort the x and the y and the z. |
|||
Write "===After sorting===" on the console. |
|||
Write "x: " then the x on the console. |
|||
Write "y: " then the y on the console. |
|||
Write "z: " then the z on the console. |
|||
To sort a first number and a second number and a third number: |
|||
If the first number is greater than the second number, swap the first number with the second number. |
|||
If the second number is greater than the third number, swap the second number with the third number. |
|||
If the first number is greater than the second number, swap the first number with the second number.</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
===Before sorting=== |
|||
x: 77444 |
|||
y: -12 |
|||
z: 0 |
|||
===After sorting=== |
|||
x: -12 |
|||
y: 0 |
|||
z: 77444 |
|||
</pre> |
|||
=={{header|PureBasic}}== |
|||
<syntaxhighlight lang="purebasic">;sort three variables: x, y, z |
|||
;Macro handles any of the native types, including integers, floating point, and strings |
|||
;because the variable types are not declared but substituted during each instance of the macro. |
|||
;The sorting is in ascending order, i.e. x < y < z. |
|||
Macro sort3vars(x, y, z) |
|||
If x > y: Swap x, y: EndIf |
|||
If x > z: Swap x, z: EndIf |
|||
If y > z: Swap y, z: EndIf |
|||
EndMacro |
|||
;Macro to perform the sorting test for each variable type, again by substitution. |
|||
Macro test_sort(x, y, z) |
|||
PrintN("Variables before sorting: " + #CRLF$ + x + #CRLF$ + y + #CRLF$ + z + #CRLF$) |
|||
sort3vars(x, y, z) |
|||
PrintN("Variables after sorting: " + #CRLF$ + x + #CRLF$ + y + #CRLF$ + z + #CRLF$) |
|||
EndMacro |
|||
;Define three sets of variables each with a different type for testing |
|||
Define.s x, y, z ;string |
|||
x = "lions, tigers, and" |
|||
y = "bears, oh my!" |
|||
z = ~"(from the \"Wizard of OZ\")" ;uses an escaped string as one way to include quotation marks |
|||
Define x1 = 77444, y1 = -12, z1 = 0 ;integer |
|||
Define.f x2= 5.2, y2 = -1133.9, z2 = 0 ;floating point |
|||
If OpenConsole() |
|||
PrintN("Sort three variables" + #CRLF$) |
|||
test_sort(x, y, z) ;strings |
|||
test_sort(x1, y1, z1) ;integers |
|||
test_sort(x2, y2, z2) ;floating point |
|||
Print(#CRLF$ + "Press ENTER to exit"): Input() |
|||
CloseConsole() |
|||
EndIf</syntaxhighlight> |
|||
Sample output: |
|||
<pre>Sort three variables |
|||
Variables before sorting: |
|||
lions, tigers, and |
|||
bears, oh my! |
|||
(from the "Wizard of OZ") |
|||
Variables after sorting: |
|||
(from the "Wizard of OZ") |
|||
bears, oh my! |
|||
lions, tigers, and |
|||
Variables before sorting: |
|||
77444 |
|||
-12 |
|||
0 |
|||
Variables after sorting: |
|||
-12 |
|||
0 |
|||
77444 |
|||
Variables before sorting: |
|||
5.1999998093 |
|||
-1133.9000244141 |
|||
0 |
|||
Variables after sorting: |
|||
-1133.9000244141 |
|||
0 |
|||
5.1999998093 |
|||
</pre> |
|||
=={{header|Python}}== |
|||
===Python2=== |
|||
This solution accepts 3 values either strings or numbers from user and then sort it in ascending order. This is implemented in Python 2. |
|||
<syntaxhighlight lang="python"> |
|||
#python2 Code for Sorting 3 values |
|||
a= raw_input("Enter values one by one ..\n1.").strip() |
|||
b=raw_input("2.").strip() |
|||
c=raw_input("3.").strip() |
|||
if a>b : |
|||
a,b = b,a |
|||
if a>c: |
|||
a,c = c,a |
|||
if b>c: |
|||
b,c = c,b |
|||
print(str(a)+" "+str(b)+" "+str(c)) |
|||
</syntaxhighlight> |
|||
===Python3=== |
|||
The following uses Python3.6 f-strings and uses the built in sorted function and assignment to a target list. |
|||
<syntaxhighlight lang="python">while True: |
|||
x, y, z = eval(input('Three Python values: ')) |
|||
print(f'As read: x = {x!r}; y = {y!r}; z = {z!r}') |
|||
x, y, z = sorted((x, y, z)) |
|||
print(f' Sorted: x = {x!r}; y = {y!r}; z = {z!r}')</syntaxhighlight> |
|||
{{out}} |
|||
<pre>Three Python values: 3, 2, 1 |
|||
As read: x = 3; y = 2; z = 1 |
|||
Sorted: x = 1; y = 2; z = 3 |
|||
Three Python values: 'lions, tigers, and', 'bears, oh my!', '(from the "Wizard of OZ")' |
|||
As read: x = 'lions, tigers, and'; y = 'bears, oh my!'; z = '(from the "Wizard of OZ")' |
|||
Sorted: x = '(from the "Wizard of OZ")'; y = 'bears, oh my!'; z = 'lions, tigers, and' |
|||
Three Python values: 77444, -12, 0 |
|||
As read: x = 77444; y = -12; z = 0 |
|||
Sorted: x = -12; y = 0; z = 77444 |
|||
Three Python values:</pre> |
|||
=={{header|Quackery}}== |
|||
Quackery does not have variables, instead it has ''ancillary stacks'', which, amongst their uses, can act as variables. Neither does it have operator overloading, so instead we will use <code>sortwith ></code> to sort three integers into ascending numerical order, and <code>sortwith $></code> to sort three strings into ascending QACSFOT order. |
|||
(QACSFOT is the Quackery Arbitrary Character Sequence For Ordered Text, which is <code>0123456789AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz()[]{}<>~=+-*/^\|_.,:;?!'"`%@&#$</code>. Note that, unlike the even more arbitrary ASCII/Unicode character sequence, all the punctuation marks come after all the alphabetic characters, so the result of sorting the strings will vary from the result given in the task description.) |
|||
<syntaxhighlight lang="quackery"> [ stack ] is x |
|||
[ stack ] is y |
|||
[ stack ] is z |
|||
$ 'lions, tigers, and' x put |
|||
$ 'bears, oh my!' y put |
|||
$ '(from the "Wizard of OZ")' z put |
|||
x take y take z take |
|||
3 pack sortwith $> unpack |
|||
z put y put x put |
|||
say " x = " x take echo$ cr |
|||
say " y = " y take echo$ cr |
|||
say " z = " z take echo$ cr |
|||
cr |
|||
77444 x put |
|||
-12 y put |
|||
0 z put |
|||
x take y take z take |
|||
3 pack sortwith > unpack |
|||
z put y put x put |
|||
say " x = " x take echo cr |
|||
say " y = " y take echo cr |
|||
say " z = " z take echo cr</syntaxhighlight> |
|||
{{out}} |
|||
<pre> x = bears, oh my! |
|||
y = lions, tigers, and |
|||
z = (from the "Wizard of OZ") |
|||
x = -12 |
|||
y = 0 |
|||
z = 77444 |
|||
</pre> |
|||
=={{header|R}}== |
|||
<syntaxhighlight lang="text"> |
|||
#lang R |
|||
assignVec <- Vectorize("assign", c("x", "value")) |
|||
`%<<-%` <- function(x, value) invisible(assignVec(x, value, envir = .GlobalEnv)) # define multiple global assignments operator |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<syntaxhighlight lang="text"> |
|||
x <- 'lions, tigers, and' |
|||
y <- 'bears, oh my!' |
|||
z <- '(from the "Wizard of OZ")' |
|||
c("x", "y", "z") %<<-% sort(c(x, y, z)) |
|||
x |
|||
## [1] "(from the \"Wizard of OZ\")" |
|||
y |
|||
## [1] "bears, oh my!" |
|||
z |
|||
## [1] "lions, tigers, and" |
|||
x <- 77444 |
|||
y <- -12 |
|||
z <- 0 |
|||
c("x", "y", "z") %<<-% sort(c(x, y, z)) |
|||
x |
|||
## [1] -12 |
|||
y |
|||
## [1] 0 |
|||
z |
|||
## [1] 77444 |
|||
</syntaxhighlight> |
|||
=={{header|Racket}}== |
|||
Ugh... mutation. Anyway... |
|||
<syntaxhighlight lang="text">#lang racket |
|||
(define-syntax-rule (sort-3! x y z <?) |
|||
(begin |
|||
(define-syntax-rule (swap! x y) (let ((tmp x)) (set! x y) (set! y tmp))) |
|||
(define-syntax-rule (sort-2! x y) (when (<? y x) (swap! x y))) |
|||
(sort-2! x y) |
|||
(sort-2! x z) |
|||
(sort-2! y z))) |
|||
(module+ test |
|||
(require rackunit |
|||
data/order) |
|||
(define (test-permutations l <?) |
|||
(test-case |
|||
(format "test-permutations ~a" (object-name <?)) |
|||
(for ((p (in-permutations l))) |
|||
(match-define (list a b c) p) |
|||
(sort-3! a b c <?) |
|||
(check-equal? (list a b c) l)))) |
|||
(test-permutations '(1 2 3) <) |
|||
;; string sorting |
|||
(let ((x "lions, tigers, and") |
|||
(y "bears, oh my!") |
|||
(z "(from the \"Wizard of OZ\")")) |
|||
(sort-3! x y z string<?) |
|||
(for-each displayln (list x y z))) |
|||
(newline) |
|||
;; general data sorting |
|||
(define datum<? (order-<? datum-order)) |
|||
(let ((x "lions, tigers, and") |
|||
(y "bears, oh my!") |
|||
(z '(from the "Wizard of OZ"))) |
|||
(sort-3! x y z datum<?) |
|||
(for-each displayln (list x y z))))</syntaxhighlight> |
|||
{{out}} |
|||
<pre>(from the "Wizard of OZ") |
|||
bears, oh my! |
|||
lions, tigers, and |
|||
bears, oh my! |
|||
lions, tigers, and |
|||
(from the Wizard of OZ)</pre> |
|||
=={{header|Raku}}== |
|||
(formerly Perl 6) |
|||
Raku has a built in sort routine which uses a variation of quicksort. The built in sort routine will automatically select a numeric sort if given a list of Real numeric items and a lexical Unicode sort if given a list that contains strings. The default numeric sort won't sort complex numbers unless you give it a custom comparator. It is trivial to modify the sort comparator function to get whatever ordering you want though. |
|||
The list (77444, -12, 0) is a poor choice to demonstrate numeric sort since it will sort the same numerically or lexically. Instead we'll use (7.7444e4, -12, 18/2). ( A Num, an Int, and a Rat. ) |
The list (77444, -12, 0) is a poor choice to demonstrate numeric sort since it will sort the same numerically or lexically. Instead we'll use (7.7444e4, -12, 18/2). ( A Num, an Int, and a Rat. ) |
||
<lang |
<syntaxhighlight lang="raku" line># Sorting strings. Added a vertical bar between strings to make them discernable |
||
my ($a, $b, $c) = 'lions, tigers, and', 'bears, oh my!', '(from "The Wizard of Oz")'; |
my ($a, $b, $c) = 'lions, tigers, and', 'bears, oh my!', '(from "The Wizard of Oz")'; |
||
say "sorting: {($a, $b, $c).join('|')}"; |
say "sorting: {($a, $b, $c).join('|')}"; |
||
Line 670: | Line 3,106: | ||
# sort ALL THE THINGS |
# sort ALL THE THINGS |
||
# sorts by lexical order with numeric values by magnitude. |
# sorts by lexical order with numeric values by magnitude. |
||
.say for ($a, $b, $c, $x, $y, $z).sort;</ |
.say for ($a, $b, $c, $x, $y, $z).sort;</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 690: | Line 3,126: | ||
lions, tigers, and</pre> |
lions, tigers, and</pre> |
||
=={{header| |
=={{header|Red}}== |
||
Red can natively sort values of various types. For instance here (not exhaustive): strings, integers, floats, characters, IP addresses, email addresses, words (~ variable names). |
|||
Phix is naturally polymorphic |
|||
<syntaxhighlight lang="red">foreach [x y z] [ |
|||
<lang Phix>object {x,y,z} = {"lions, tigers, and","bears, oh my","(from the \"Wizard of OZ\")"} |
|||
"lions, tigers, and" |
|||
?{x,y,z} |
|||
"bears, oh my!" |
|||
{x,y,z} = sort({x,y,z}) |
|||
{(from the "Wizard of OZ")} |
|||
?{x,y,z} |
|||
77444 -12 0 |
|||
3.1416 3.1415926 3.141592654 |
|||
{x,y,z} = {77444,-12,0} |
|||
#"z" #"0" #"A" |
|||
?{x,y,z} |
|||
216.239.36.21 172.67.134.114 127.0.0.1 |
|||
{x,y,z} = sort({x,y,z}) |
|||
john@doe.org max@min.com cool@bi.net |
|||
?{x,y,z}</lang> |
|||
potato carrot cabbage |
|||
][ |
|||
set [x y z] sort reduce [x y z] |
|||
print ["x:" mold x "y:" mold y "z:" mold z] |
|||
]</syntaxhighlight> |
|||
{{out}} |
{{out}} |
||
<pre>x: {(from the "Wizard of OZ")} y: "bears, oh my!" z: "lions, tigers, and" |
|||
<pre> |
|||
x: -12 y: 0 z: 77444 |
|||
{"lions, tigers, and","bears, oh my","(from the \"Wizard of OZ\")"} |
|||
x: 3.1415926 y: 3.141592654 z: 3.1416 |
|||
{"(from the \"Wizard of OZ\")","bears, oh my","lions, tigers, and"} |
|||
x: #"0" y: #"A" z: #"z" |
|||
{77444,-12,0} |
|||
x: 127.0.0.1 y: 172.67.134.114 z: 216.239.36.21 |
|||
{-12,0,77444} |
|||
x: cool@bi.net y: john@doe.org z: max@min.com |
|||
</pre> |
|||
x: cabbage y: carrot z: potato</pre> |
|||
=={{header|PicoLisp}}== |
|||
<lang PicoLisp>(let (X 77444 Y -12 Z 0) |
|||
(println X Y Z) |
|||
(mapc set '(X Y Z) (sort (list X Y Z))) |
|||
(println X Y Z) )</lang> |
|||
{{out}} |
|||
<pre>77444 -12 0 |
|||
-12 0 77444</pre> |
|||
=={{header|REXX}}== |
=={{header|REXX}}== |
||
Line 724: | Line 3,157: | ||
The literals can be of any length (only limited by virtual memory or language limitations). |
The literals can be of any length (only limited by virtual memory or language limitations). |
||
< |
<syntaxhighlight lang="rexx">/*REXX program sorts three (any value) variables (X, Y, and Z) into ascending order.*/ |
||
parse arg x y z . /*obtain the three variables from C.L. */ |
parse arg x y z . /*obtain the three variables from C.L. */ |
||
if x=='' | x=="," then x= 'lions, tigers, and' /*Not specified? Use the default*/ |
if x=='' | x=="," then x= 'lions, tigers, and' /*Not specified? Use the default*/ |
||
Line 732: | Line 3,165: | ||
say '───── original value of Y: ' y |
say '───── original value of Y: ' y |
||
say '───── original value of Z: ' z |
say '───── original value of Z: ' z |
||
if x>y then do; _=x; x=y; y=_; |
if x>y then do; _= x; x= y; y= _; end /*swap the values of X and Y. */ /* ◄─── sorting.*/ |
||
if y>z then do; _=y; y=z; z=_; |
if y>z then do; _= y; y= z; z= _; end /* " " " " Y " Z. */ /* ◄─── sorting.*/ |
||
if x>y then do; _=x; x=y; y=_; |
if x>y then do; _= x; x= y; y= _; end /* " " " " X " Y. */ /* ◄─── sorting */ |
||
say /*stick a fork in it, we're all done. */ |
say /*stick a fork in it, we're all done. */ |
||
say '═════ sorted value of X: ' x |
say '═════ sorted value of X: ' x |
||
say '═════ sorted value of Y: ' y |
say '═════ sorted value of Y: ' y |
||
say '═════ sorted value of Z: ' z</ |
say '═════ sorted value of Z: ' z</syntaxhighlight> |
||
{{out|output|text= |
{{out|output|text=when using the default inputs:}} |
||
<pre> |
<pre> |
||
───── original value of X: lions, tigers, and |
───── original value of X: lions, tigers, and |
||
Line 754: | Line 3,187: | ||
The maximum integer than be kept ''as an integer'' is (in this program) is 1,000 decimal digits. |
The maximum integer than be kept ''as an integer'' is (in this program) is 1,000 decimal digits. |
||
< |
<syntaxhighlight lang="rexx">/*REXX program sorts three (numeric) variables (X, Y, and Z) into ascending order. */ |
||
numeric digits 1000 /*handle some pretty gihugic integers. */ /*can be bigger.*/ |
numeric digits 1000 /*handle some pretty gihugic integers. */ /*can be bigger.*/ |
||
parse arg x y z . /*obtain the three variables from C.L. */ |
parse arg x y z . /*obtain the three variables from C.L. */ |
||
Line 760: | Line 3,193: | ||
if y=='' | y=="," then y= -12 /* " " " " " " */ |
if y=='' | y=="," then y= -12 /* " " " " " " */ |
||
if z=='' | z=="," then z= 0 /* " " " " " " */ |
if z=='' | z=="," then z= 0 /* " " " " " " */ |
||
w=max( length(x), length(y), length(z) ) + 5 |
w= max( length(x), length(y), length(z) ) + 5 /*find max width of the values, plus 5.*/ |
||
say '───── original values of X, Y, and Z: ' right(x, w) right(y, w) right(z, w) |
say '───── original values of X, Y, and Z: ' right(x, w) right(y, w) right(z, w) |
||
low = x /*assign a temporary variable. |
low = x /*assign a temporary variable. */ |
||
mid = y /* " " " " |
mid = y /* " " " " */ |
||
high= z /* " " " " |
high= z /* " " " " */ |
||
x=min(low, mid, high) |
x= min(low, mid, high) /*determine the lowest value of X,Y,Z. */ /* ◄─── sorting.*/ |
||
z=max(low, mid, high) |
z= max(low, mid, high) /* " " highest " " " " " */ /* ◄─── sorting.*/ |
||
y= low + mid + high - x - z |
y= low + mid + high - x - z /* " " middle " " " " " */ /* ◄─── sorting.*/ |
||
/*stick a fork in it, we're all done. */ |
/*stick a fork in it, we're all done. */ |
||
say '═════ sorted values of X, Y, and Z: ' |
say '═════ sorted values of X, Y, and Z: ' right(x, w) right(y, w) right(z, w)</syntaxhighlight> |
||
{{out|output|text= when using the default inputs:}} |
{{out|output|text= when using the default inputs:}} |
||
<pre> |
<pre> |
||
Line 775: | Line 3,208: | ||
═════ sorted values of X, Y, and Z: -12 0 77444 |
═════ sorted values of X, Y, and Z: -12 0 77444 |
||
</pre> |
</pre> |
||
=={{header|Ring}}== |
|||
<syntaxhighlight lang="ring"># Project : Sort three variables |
|||
x = 'lions, tigers, and' |
|||
y = 'bears, oh my!' |
|||
z = '(from the "Wizard of OZ")' |
|||
sortthree(x,y,z) |
|||
x = 77444 |
|||
y = -12 |
|||
z = 0 |
|||
sortthree(x,y,z) |
|||
func sortthree(x,y,z) |
|||
str = [] |
|||
add(str,x) |
|||
add(str,y) |
|||
add(str,z) |
|||
str = sort(str) |
|||
see "x = " + str[1] + nl |
|||
see "y = " + str[2] + nl |
|||
see "z = " + str[3] + nl |
|||
see nl |
|||
</syntaxhighlight> |
|||
Output: |
|||
<pre>x = (from the "Wizard of OZ") |
|||
y = bears, oh my! |
|||
z = lions, tigers, and |
|||
x = -12 |
|||
y = 0 |
|||
z = 77444</pre> =={{header|Ring}}== |
|||
<syntaxhighlight lang="ring">x = 77444 |
|||
y = -12 |
|||
z = 0 |
|||
sList = sortList(x, y, z) |
|||
see sList + nl |
|||
x = 'lions, tigers, and' |
|||
y = 'bears, oh my!' |
|||
z = '(from the "Wizard of OZ")' |
|||
sList = sortList(x, y, z) |
|||
see sList + nl |
|||
func sortList (x, y, z) |
|||
aList = [x, y, z] |
|||
sList = sort(aList) |
|||
return sList |
|||
</syntaxhighlight> |
|||
Output: |
|||
<pre>-12 |
|||
0 |
|||
77444 |
|||
(from the "Wizard of OZ") |
|||
bears, oh my! |
|||
lions, tigers, and</pre> |
|||
=={{header|RPL}}== |
|||
{{works with|HP|48}} |
|||
≪ → x y z |
|||
≪ x y z 3 →LIST SORT LIST→ DROP |
|||
≫ ≫ '<span style="color:blue">SORT3</span>' STO |
|||
"lions, tigers, and" "bears, oh my!" "(from the 'Wizard of OZ')" <span style="color:blue">SORT3</span> |
|||
77444 -12 9 <span style="color:blue">SORT3</span> |
|||
{{out}} |
|||
<pre> |
|||
6: "bears, oh my!" |
|||
5: "lions, tigers, and" |
|||
4: "(from the 'Wizard of OZ')" |
|||
3: -12 |
|||
2: 9 |
|||
1: 77444 |
|||
</pre> |
|||
=={{header|Ruby}}== |
|||
<syntaxhighlight lang="ruby">x = 'lions, tigers, and' |
|||
y = 'bears, oh my!' |
|||
z = '(from the "Wizard of OZ")' |
|||
x, y, z = [x, y, z].sort |
|||
puts x, y, z |
|||
x, y, z = 7.7444e4, -12, 18/2r # Float, Integer, Rational; taken from Raku |
|||
x, y, z = [x, y, z].sort |
|||
puts x, y, z |
|||
</syntaxhighlight> |
|||
{{Out}} |
|||
<pre>(from the "Wizard of OZ") |
|||
bears, oh my! |
|||
lions, tigers, and |
|||
-12 |
|||
9/1 |
|||
77444.0</pre> |
|||
=={{header|Rust}}== |
|||
<syntaxhighlight lang="rust">fn main() { |
|||
let mut array = [5, 1, 3]; |
|||
array.sort(); |
|||
println!("Sorted: {:?}", array); |
|||
array.sort_by(|a, b| b.cmp(a)); |
|||
println!("Reverse sorted: {:?}", array); |
|||
} |
|||
</syntaxhighlight> |
|||
==Scala== |
|||
As a Functional Programming language embraces the use of immutable variables. Mutability (variables and states) is seen as evil. Scala works rather with transformed collection obtained by functions then mutable variable and variable state. So this task has no sense in modern programming. |
|||
=={{header|Seed7}}== |
|||
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i"; |
|||
const proc: genSort3 (in type: elemType) is func |
|||
begin |
|||
global |
|||
const proc: doSort3 (in var elemType: x, in var elemType: y, in var elemType: z) is func |
|||
local |
|||
var array elemType: sorted is 0 times elemType.value; |
|||
begin |
|||
writeln("BEFORE: x=[" <& x <& "]; y=[" <& y <& "]; z=[" <& z <& "]"); |
|||
sorted := sort([](x, y, z)); |
|||
x := sorted[1]; |
|||
y := sorted[2]; |
|||
z := sorted[3]; |
|||
writeln("AFTER: x=[" <& x <& "]; y=[" <& y <& "]; z=[" <& z <& "]"); |
|||
end func; |
|||
end global; |
|||
end func; |
|||
genSort3(integer); |
|||
genSort3(string); |
|||
const proc: main is func |
|||
begin |
|||
doSort3(77444, -12, 0); |
|||
doSort3("lions, tigers, and", "bears, oh my!", "(from the \"Wizard of OZ\")"); |
|||
end func;</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
BEFORE: x=[77444]; y=[-12]; z=[0] |
|||
AFTER: x=[-12]; y=[0]; z=[77444] |
|||
BEFORE: x=[lions, tigers, and]; y=[bears, oh my!]; z=[(from the "Wizard of OZ")] |
|||
AFTER: x=[(from the "Wizard of OZ")]; y=[bears, oh my!]; z=[lions, tigers, and] |
|||
</pre> |
|||
=={{header|SenseTalk}}== |
|||
<syntaxhighlight lang="sensetalk">Set x to "lions, tigers and" |
|||
Set y to "bears, oh my!" |
|||
Set z to "(from the Wizard of Oz)" |
|||
log x |
|||
log y |
|||
log z |
|||
set RosettaListAlpha to (x,y,z) |
|||
log RosettaListAlpha |
|||
sort RosettaListAlpha alphabetically |
|||
log RosettaListAlpha |
|||
LogSuccess "Alphabetical Sort Successful" |
|||
set (x,y,z) to RosettaListAlpha |
|||
log x |
|||
log y |
|||
log z |
|||
LogSuccess "Sorted Items back into Original Variables" |
|||
Set a to "77444" |
|||
set b to "-12" |
|||
set c to "0" |
|||
set d to "62224" |
|||
set RosettaListNum to (a,b,c,d) |
|||
log RosettaListNum |
|||
sort RosettaListNum numerically |
|||
log RosettaListNum |
|||
LogSuccess "Numerical Sort Successful" |
|||
set (a,b,c,d) to RosettaListNum |
|||
log a |
|||
log b |
|||
log c |
|||
log d |
|||
LogSuccess "Sorted Numbers back into Original Variables"</syntaxhighlight> |
|||
=={{header|Sidef}}== |
=={{header|Sidef}}== |
||
Generalized solution, for an arbitrary number of variable references: |
Generalized solution, for an arbitrary number of variable references: |
||
< |
<syntaxhighlight lang="ruby">func sort_refs(*arr) { |
||
arr.map{ *_ }.sort ~Z arr -> each { *_[1] = _[0] } |
arr.map{ *_ }.sort ~Z arr -> each { *_[1] = _[0] } |
||
} |
} |
||
Line 790: | Line 3,413: | ||
say x |
say x |
||
say y |
say y |
||
say z</ |
say z</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre>-12 |
||
-12 |
|||
0 |
0 |
||
77444 |
77444</pre> |
||
</pre> |
|||
Alternatively, without using a sorting function: |
Alternatively, without using a sorting function: |
||
< |
<syntaxhighlight lang="ruby">var x = 77444 |
||
var y = -12 |
var y = -12 |
||
var z = 0 |
var z = 0 |
||
Line 808: | Line 3,429: | ||
say x |
say x |
||
say y |
say y |
||
say z</ |
say z</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre>-12 |
||
-12 |
|||
0 |
0 |
||
77444 |
77444</pre> |
||
=={{header|Swift}}== |
|||
<syntaxhighlight lang="swift">func varSort<T: Comparable>(_ x: inout T, _ y: inout T, _ z: inout T) { |
|||
let res = [x, y, z].sorted() |
|||
x = res[0] |
|||
y = res[1] |
|||
z = res[2] |
|||
} |
|||
var x = "lions, tigers, and" |
|||
var y = "bears, oh my!" |
|||
var z = "(from the \"Wizard of OZ\")" |
|||
print("Before:") |
|||
print("x = \(x)") |
|||
print("y = \(y)") |
|||
print("z = \(z)") |
|||
print() |
|||
varSort(&x, &y, &z) |
|||
print("After:") |
|||
print("x = \(x)") |
|||
print("y = \(y)") |
|||
print("z = \(z)")</syntaxhighlight> |
|||
{{out}} |
|||
<pre>Before: |
|||
x = lions, tigers, and |
|||
y = bears, oh my! |
|||
z = (from the "Wizard of OZ") |
|||
After: |
|||
x = (from the "Wizard of OZ") |
|||
y = bears, oh my! |
|||
z = lions, tigers, and</pre> |
|||
=={{header|Tcl}}== |
|||
<syntaxhighlight lang="tcl"> |
|||
set x {lions, tigers, and} |
|||
set y {bears, oh my!} |
|||
set z {(from the "Wizard of OZ")} |
|||
lassign [lsort [list $x $y $z]] x y z |
|||
puts "x: $x" |
|||
puts "y: $y" |
|||
puts "z: $z" |
|||
set x 77444 |
|||
set y -12 |
|||
set z 0 |
|||
lassign [lsort [list $x $y $z]] x y z |
|||
puts "x: $x" |
|||
puts "y: $y" |
|||
puts "z: $z" |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
x: (from the "Wizard of OZ") |
|||
y: bears, oh my! |
|||
z: lions, tigers, and |
|||
x: -12 |
|||
y: 0 |
|||
z: 77444 |
|||
</pre> |
|||
=={{header|TXR}}== |
|||
The following is a comprehensive solution to the general problem of sorting any number of mutable places. We develop a macro operator called <code>sort-places</code> which is called with zero or more argument expressions that denote assignable places. The places are sorted in order according to the <code>greater</code> function. |
|||
The zero and one argument cases are handled as no-ops; the arguments are not evaluated at all, even for their side effects if they have any. The two argument case is handled by generating a conditional which controls a single swap. The three-argument case performs up to three swaps. |
|||
For four or more arguments, a hidden vector object is generated. The values of the places are stuffed into the vector, which is then sorted, after which the values are retrieved and stored in the places. |
|||
'''All cases work in such a way that the place expressions are evaluated at most once,''' which is achieved by leveraging the simple-to-use <code>placelet</code> macro. |
|||
<syntaxhighlight lang="txrlisp">(defmacro sort-places (. places) |
|||
(caseql (len places) |
|||
((0 1) nil) |
|||
(2 (with-gensyms (p0 p1) |
|||
^(placelet ((p0 (read-once ,[places 0])) |
|||
(p1 (read-once ,[places 1]))) |
|||
(if (greater p0 p1) |
|||
(swap p0 p1))))) |
|||
(3 (with-gensyms (p0 p1 p2) |
|||
^(placelet ((p0 (read-once ,[places 0])) |
|||
(p1 (read-once ,[places 1])) |
|||
(p2 (read-once ,[places 2]))) |
|||
(if (greater p0 p1) |
|||
(swap p0 p1)) |
|||
(if (greater p1 p2) |
|||
(swap p1 p2)) |
|||
(if (greater p0 p1) |
|||
(swap p0 p1))))) |
|||
(t (let ((gens [mapcar (ret (gensym)) places])) |
|||
(with-gensyms (vec) |
|||
^(placelet ,(zip gens places) |
|||
(let ((,vec (vec ,*gens))) |
|||
(nsort ,vec) |
|||
(set ,*(append-each ((g gens) |
|||
(i 0)) |
|||
^(,g [,vec ,i])))))))))) |
|||
(prinl (sort-places)) |
|||
(let ((x 1)) |
|||
(sort-places x) |
|||
(prinl x)) |
|||
(let ((x 2) |
|||
(y 1)) |
|||
(sort-places x y) |
|||
(prinl (list x y))) |
|||
(let ((a 3) |
|||
(b 2) |
|||
(c 1)) |
|||
(sort-places a b c) |
|||
(prinl (list a b c))) |
|||
(let ((a 4) |
|||
(b 3) |
|||
(c 2) |
|||
(d 1)) |
|||
(sort-places a b c d) |
|||
(prinl (list a b c d)))</syntaxhighlight> |
|||
{{out}} |
|||
<pre>nil |
|||
1 |
|||
(1 2) |
|||
(1 2 3) |
|||
(1 2 3 4)</pre> |
|||
=={{header|Visual Basic .NET}}== |
|||
{{trans|C#}} |
|||
<syntaxhighlight lang="vbnet">Module Module1 |
|||
Sub Swap(Of T)(ByRef a As T, ByRef b As T) |
|||
Dim c = a |
|||
a = b |
|||
b = c |
|||
End Sub |
|||
Sub Sort(Of T As IComparable(Of T))(ByRef a As T, ByRef b As T, ByRef c As T) |
|||
If a.CompareTo(b) > 0 Then |
|||
Swap(a, b) |
|||
End If |
|||
If a.CompareTo(c) > 0 Then |
|||
Swap(a, c) |
|||
End If |
|||
If b.CompareTo(c) > 0 Then |
|||
Swap(b, c) |
|||
End If |
|||
End Sub |
|||
Sub Main() |
|||
Dim x = 77444 |
|||
Dim y = -12 |
|||
Dim z = 0 |
|||
Sort(x, y, z) |
|||
Console.WriteLine((x, y, z)) |
|||
Dim a = "lions, tigers, and" |
|||
Dim b = "bears, oh my!" |
|||
Dim c = "(from the 'Wizard of OZ')" |
|||
Sort(a, b, c) |
|||
Console.WriteLine((a, b, c)) |
|||
End Sub |
|||
End Module</syntaxhighlight> |
|||
{{out}} |
|||
<pre>(-12, 0, 77444) |
|||
((from the 'Wizard of OZ'), bears, oh my!, lions, tigers, and)</pre> |
|||
=={{header|Wren}}== |
|||
{{libheader|Wren-sort}} |
|||
{{libheader|Wren-fmt}} |
|||
<syntaxhighlight lang="wren">import "./sort" for Sort |
|||
import "./fmt" for Fmt |
|||
var sort3 = Fn.new { |x, y, z| |
|||
var a = [x, y, z] |
|||
Sort.insertion(a) |
|||
x = a[0] |
|||
y = a[1] |
|||
z = a[2] |
|||
Fmt.print(" x = $s\n y = $s\n z = $s", x, y, z) |
|||
} |
|||
System.print("After sorting strings:") |
|||
var x = "lions, tigers, and" |
|||
var y = "bears, oh my!" |
|||
var z = "(from the \"Wizard of OZ\")" |
|||
sort3.call(x, y, z) |
|||
System.print("\nAfter sorting integers:") |
|||
x = 77444 |
|||
y = -12 |
|||
z = 0 |
|||
sort3.call(x, y, z) |
|||
System.print("\nAfter sorting floats:") |
|||
x = 11.3 |
|||
y = -9.7 |
|||
z = 11.17 |
|||
sort3.call(x, y, z)</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
After sorting strings: |
|||
x = (from the "Wizard of OZ") |
|||
y = bears, oh my! |
|||
z = lions, tigers, and |
|||
After sorting integers: |
|||
x = -12 |
|||
y = 0 |
|||
z = 77444 |
|||
After sorting floats: |
|||
x = -9.7 |
|||
y = 11.17 |
|||
z = 11.3 |
|||
</pre> |
</pre> |
||
=={{header|zkl}}== |
=={{header|zkl}}== |
||
This solution uses list assignment and list sorting. Lists are not homogeneous, but sorting usually expects that. If that is a problem, you can give the sort a compare function. Numbers (real and integer) are homogeneous enough to sort. |
This solution uses list assignment and list sorting. Lists are not homogeneous, but sorting usually expects that. If that is a problem, you can give the sort a compare function. Numbers (real and integer) are homogeneous enough to sort. |
||
< |
<syntaxhighlight lang="zkl">x,y,z := "lions, tigers, and", "bears, oh my!", 0'|(from the "Wizard of OZ")|; |
||
x,y,z = List(x,y,z).sort(); |
x,y,z = List(x,y,z).sort(); |
||
println(x," | ",y," | ",z); |
println(x," | ",y," | ",z); |
||
Line 824: | Line 3,676: | ||
x,y,z := 77444, -12, 0; |
x,y,z := 77444, -12, 0; |
||
x,y,z = List(x,y,z).sort(); |
x,y,z = List(x,y,z).sort(); |
||
println(x," ",y," ",z);</ |
println(x," ",y," ",z);</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>(from the "Wizard of OZ") | bears, oh my! | lions, tigers, and |
|||
<pre> |
|||
-12 0 77444</pre> |
|||
(from the "Wizard of OZ") | bears, oh my! | lions, tigers, and |
|||
-12 0 77444 |
|||
</pre> |
|||
=={{header|Python}}== |
|||
This solution accepts 3 values either strings or numbers from user and then sort it in ascending order. This is implemented in Python 2. |
|||
<pre> |
|||
#python2 Code for Sorting 3 values |
|||
a= raw_input("Enter values one by one ..\n1.").strip() |
|||
b=raw_input("2.").strip() |
|||
c=raw_input("3.").strip() |
|||
if a>b : |
|||
a,b = b,a |
|||
if a>c: |
|||
a,c = c,a |
|||
if b>c: |
|||
b,c = c,b |
|||
print(str(a)+" "+str(b)+" "+str(c)) |
|||
</pre> |
Latest revision as of 06:20, 12 March 2024
![Task](http://static.miraheze.org/rosettacodewiki/thumb/b/ba/Rcode-button-task-crushed.png/64px-Rcode-button-task-crushed.png)
You are encouraged to solve this task according to the task description, using any language you may know.
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
Heap sort | Merge sort | Patience sort | Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
- Task
Sort (the values of) three variables (X, Y, and Z) that contain any value (numbers and/or literals).
If that isn't possible in your language, then just sort numbers (and note if they can be floating point, integer, or other).
I.E.: (for the three variables x, y, and z), where:
x = 'lions, tigers, and' y = 'bears, oh my!' z = '(from the "Wizard of OZ")'
After sorting, the three variables would hold:
x = '(from the "Wizard of OZ")' y = 'bears, oh my!' z = 'lions, tigers, and'
For numeric value sorting, use: I.E.: (for the three variables x, y, and z), where:
x = 77444 y = -12 z = 0
After sorting, the three variables would hold:
x = -12 y = 0 z = 77444
The variables should contain some form of a number, but specify if the algorithm used can be for floating point or integers. Note any limitations.
The values may or may not be unique.
The method used for sorting can be any algorithm; the goal is to use the most idiomatic in the computer programming language used.
More than one algorithm could be shown if one isn't clearly the better choice.
One algorithm could be:
• store the three variables x, y, and z into an array (or a list) A • sort (the three elements of) the array A • extract the three elements from the array and place them in the variables x, y, and z in order of extraction
Another algorithm (only for numeric values):
x= 77444 y= -12 z= 0 low= x mid= y high= z x= min(low, mid, high) /*determine the lowest value of X,Y,Z. */ z= max(low, mid, high) /* " " highest " " " " " */ y= low + mid + high - x - z /* " " middle " " " " " */
Show the results of the sort here on this page using at least the values of those shown above.
11l
V x = 77444
V y = -12
V z = 0
(x, y, z) = tuple_sorted((x, y, z))
print(x‘ ’y‘ ’z)
V xs = ‘lions, tigers, and’
V ys = ‘bears, oh my!’
V zs = ‘(from the "Wizard of OZ")’
(xs, ys, zs) = sorted([xs, ys, zs])
print(xs"\n"ys"\n"zs)
- Output:
-12 0 77444 (from the "Wizard of OZ") bears, oh my! lions, tigers, and
8086 Assembly
Sorting Unsigned Integers
mov ax,6FFFh
mov bx,3456h
mov cx,0
;We'll consider these sorted when ax <= bx <= cx.
SortRegisters proc
cmp ax,bx
jbe continue
;if we got here, ax > bx. We don't know the relationship between bx and cx at this time.
cmp ax,cx
jbe swap_ax_and_bx
;if we got here, ax > bx, and bx > cx. Therefore all we need to do is swap ax and cx, and we're done.
xchg ax,cx
jmp endOfProc
swap ax_and_bx:
;if we got here, ax > bx, and ax <= cx. So all we have to do is swap ax and bx, and we're done
xchg ax,bx
jmp end ;back to top
continue: ;if we got here, ax <= bx.
cmp bx,cx
jbe end
;if we got here, ax <= bx, and bx > cx. Therefore all we need to do is swap bx and cx, and we're done.
xchg bx,cx
endOfProc: ;if we got here, ax <= bx, and bx <= cx. Therefore, ax <= bx <=cx and we are done.
;
SortRegisters endp
Ada
with Ada.Text_IO;
with Ada.Strings.Unbounded;
procedure Sort_Three is
generic
type Element_Type is private;
with function "<" (Left, Right : in Element_Type) return Boolean;
procedure Generic_Sort (X, Y, Z : in out Element_Type);
procedure Generic_Sort (X, Y, Z : in out Element_Type)
is
procedure Swap (Left, Right : in out Element_Type) is
T : constant Element_Type := Left;
begin
Left := Right;
Right := T;
end Swap;
begin
if Y < X then Swap (X, Y); end if;
if Z < Y then Swap (Y, Z); end if;
if Y < X then Swap (X, Y); end if;
end Generic_Sort;
procedure Test_Unbounded_Sort is
use Ada.Text_IO;
use Ada.Strings.Unbounded;
X : Unbounded_String := To_Unbounded_String ("lions, tigers, and");
Y : Unbounded_String := To_Unbounded_String ("bears, oh my!");
Z : Unbounded_String := To_Unbounded_String ("(from the ""Wizard of OZ"")");
procedure Sort is
new Generic_Sort (Unbounded_String, "<");
begin
Sort (X, Y, Z);
Put_Line (To_String (X));
Put_Line (To_String (Y));
Put_Line (To_String (Z));
New_Line;
End Test_Unbounded_Sort;
procedure Test_Integer_Sort is
use Ada.Text_IO;
procedure Sort is
new Generic_Sort (Integer, "<");
X : Integer := 77444;
Y : Integer := -12;
Z : Integer := 0;
begin
Sort (X, Y, Z);
Put_Line (X'Image);
Put_Line (Y'Image);
Put_Line (Z'Image);
New_Line;
end Test_Integer_Sort;
begin
Test_Unbounded_Sort;
Test_Integer_Sort;
end Sort_Three;
- Output:
(from the "Wizard of OZ") bears, oh my! lions, tigers, and -12 0 77444
Aime
integer a, b, c;
index i;
text x, y, z;
record r;
x = "lions, tigers, and";
y = "bears, oh my!";
z = "(from the \"Wizard of OZ\")";
r.fit(x, x, y, y, z, z);
x = r.rf_pick;
y = r.rf_pick;
z = r.rf_pick;
o_form("~\n~\n~\n", x, y, z);
a = 77444;
b = -12;
c = 0;
i.fit(a, a, b, b, c, c);
a = i.if_pick;
b = i.if_pick;
c = i.if_pick;
o_form("~\n~\n~\n", a, b, c);
- Output:
(from the "Wizard of OZ") bears, oh my! lions, tigers, and -12 0 77444
ALGOL 68
This uses Algol 68's UNION facility which allows a variable to have values of a number of types whilst maintaining Algol 68's strong-typing.
Assignment allows any value of one of the UNION MODEs to be directly assigned to the variable.
When using the variable, its MODE (type) and value must be tested and extracted using a CASE construct.
As the task only requires sorting three values, we use a simple, three-element specific sort routine.
BEGIN
# MODE that can hold integers and strings - would need to be extended to #
# allow for other types #
MODE INTORSTRING = UNION( INT, STRING );
# returns TRUE if a is an INT, FALSE otherwise #
OP ISINT = ( INTORSTRING a )BOOL: CASE a IN (INT): TRUE OUT FALSE ESAC;
# returns TRUE if a is an INT, FALSE otherwise #
OP ISSTRING = ( INTORSTRING a )BOOL: CASE a IN (STRING): TRUE OUT FALSE ESAC;
# returns the integer in a or 0 if a isn't an integer #
OP TOINT = ( INTORSTRING a )INT: CASE a IN (INT i): i OUT 0 ESAC;
# returns the string in a or "" if a isn't a string #
OP TOSTRING = ( INTORSTRING a )STRING: CASE a IN (STRING s): s OUT "" ESAC;
# returns TRUE if a < b, FALSE otherwise #
# a and b must have the same type #
PRIO LESSTHAN = 4;
OP LESSTHAN = ( INTORSTRING a, b )BOOL:
IF ISSTRING a AND ISSTRING b THEN
# both strings #
TOSTRING a < TOSTRING b
ELIF ISINT a AND ISINT b THEN
# both integers #
TOINT a < TOINT b
ELSE
# different MODEs #
FALSE
FI # LESSTHAN # ;
# exchanges the values of a and b #
PRIO SWAP = 9;
OP SWAP = ( REF INTORSTRING a, b )VOID: BEGIN INTORSTRING t := a; a := b; b := t END;
# sorts a, b and c #
PROC sort 3 = ( REF INTORSTRING a, b, c )VOID:
BEGIN
IF b LESSTHAN a THEN a SWAP b FI;
IF c LESSTHAN a THEN a SWAP c FI;
IF c LESSTHAN b THEN b SWAP c FI
END # sort 3 # ;
# task test cases #
INTORSTRING x, y, z;
x := "lions, tigers, and";
y := "bears, oh my!";
z := "(from the ""Wizard of OZ"")";
sort 3( x, y, z );
print( ( x, newline, y, newline, z, newline ) );
x := 77444;
y := -12;
z := 0;
sort 3( x, y, z );
print( ( x, newline, y, newline, z, newline ) )
END
- Output:
(from the "Wizard of OZ") bears, oh my! lions, tigers, and -12 +0 +77444
Amazing Hopper
#include <basico.h>
algoritmo
x = 77444, y = -12.5, z = 0
low=x, midd=y, high=z
imprimir("BEFORE:\nX = ",x, " Y = ",y, " Z = ",z,NL)
#basic{
x = min( min( low,midd),high)
z = max( max( low,midd),high)
y = low + midd + high - x - z
}
imprimir("\nAFTER:\nX = ",x, " Y = ",y, " Z = ",z,NL,NL)
x = "lions, tigers, and"
y = "bears, oh my!"
z = "(from the \"Wizard of OZ\")"
imprimir("BEFORE:\nX = ",x, "\nY = ",y, "\nZ = ",z,NL)
#(x > y), entonces { intercambiar( x,y) }
#(y > z), entonces {
intercambiar (y,z )
#(x > y), entonces { intercambiar( x,y ) }
}
imprimir("\nAFTER:\nX = ",x, "\nY = ",y, "\nZ = ",z,NL,NL)
p = {}
'"lions, tigers, and",77444,"bears, oh my!",-12.7,0,"(from the \"Wizard of OZ\")"'
enlistar en 'p'
fijar separador 'NL'
imprimir("BEFORE:\n",p,NL)
matriz.ordenar(p)
imprimir("\nAFTER:\n",p,NL)
terminar
- Output:
$ hopper3 basica/sort3var.bas BEFORE: X = 77444 Y = -12.500000 Z = 0 AFTER: X = -12.500000 Y = 0.000000 Z = 77444.000000 BEFORE: X = lions, tigers, and Y = bears, oh my! Z = (from the "Wizard of OZ") AFTER: X = (from the "Wizard of OZ") Y = bears, oh my! Z = lions, tigers, and BEFORE: lions, tigers, and 77444 bears, oh my! -12.700000 0 (from the "Wizard of OZ") AFTER: (from the "Wizard of OZ") bears, oh my! lions, tigers, and -12.700000 0 77444
APL
Works in Dyalog APL. Assumes x,y,z are already defined.
x y z←{⍵[⍋⍵]}x y z
Uses destructuring assignment syntax.
AppleScript
set x to "lions, tigers, and"
set y to "bears, oh my!"
set z to "(from the \"Wizard of OZ\")"
if (x > y) then set {x, y} to {y, x}
if (y > z) then
set {y, z} to {z, y}
if (x > y) then set {x, y} to {y, x}
end if
return {x, y, z}
- Output:
{"(from the \"Wizard of OZ\")", "bears, oh my!", "lions, tigers, and"}
set x to 77444
set y to -12
set z to 0
if (x > y) then set {x, y} to {y, x}
if (y > z) then
set {y, z} to {z, y}
if (x > y) then set {x, y} to {y, x}
end if
return {x, y, z}
- Output:
{-12, 0, 77444}
Longer, but more efficiently:
set x to "lions, tigers, and"
set y to "bears, oh my!"
set z to "(from the \"Wizard of OZ\")"
tell x
if (it > y) then
set x to y
set y to it
end if
end tell
tell z
if (it < y) then
set z to y
if (it < x) then
set y to x
set x to it
else
set y to it
end if
end if
end tell
return {x, y, z}
Arturo
x: {lions, tigers, and}
y: {bears, oh my!}
z: {(from the "Wizard of OZ")}
print join.with:"\n" sort @[x y z]
x: 125
y: neg 2
z: pi
print sort @[x y z]
- Output:
(from the "Wizard of OZ") bears, oh my! lions, tigers, and -2 3.141592653589793 125
AutoHotkey
SortThreeVariables(ByRef x,ByRef y,ByRef z){
obj := []
for k, v in (var := StrSplit("x,y,z", ","))
obj[%v%] := true
for k, v in obj
temp := var[A_Index], %temp% := k
}
Examples:
x = lions, tigers, and
y = bears, oh my!
z = (from the "Wizard of OZ")
SortThreeVariables(x,y,z)
MsgBox % x "`n" y "`n" z
x = 77444
y = -12
z = 0
SortThreeVariables(x,y,z)
MsgBox % x "`n" y "`n" z
return
Outputs:
--------------------------- (from the "Wizard of OZ") bears, oh my! lions, tigers, and --------------------------- -12 0 77444 ---------------------------
BCPL
BCPL is typeless: every variable is simply a machine word, and it is the operators that are used that decide how to treat their input. Therefore, this function uses an external comparator function to decide how the three variables should be ordered.
The code below uses sort3
to sort both integers and strings
(i.e., pointers to vectors of characters packed into machine words).
To make it work with floating-point numbers, on a compiler that supports them,
all one would need to do is define a third comparator.
get "libhdr"
// Sort 3 variables using a comparator.
// X, Y and Z are pointers.
let sort3(comp, x, y, z) be
$( sort2(comp, x, y)
sort2(comp, x, z)
sort2(comp, y, z)
$)
and sort2(comp, x, y) be
if comp(!x, !y) > 0
$( let t = !x
!x := !y
!y := t
$)
// Integer and string comparators
let intcomp(x, y) = x - y
let strcomp(x, y) = valof
$( for i=1 to min(x%0, y%0)
unless x%i = y%i
resultis intcomp(x%i, y%i)
resultis intcomp(x%0, y%0)
$)
and min(x, y) = x < y -> x, y
// Run the function on both ints and strings
let start() be
$( printAndSort(writen, intcomp, 7444, -12, 0)
printAndSort(writes, strcomp,
"lions, tigers, and",
"bears, oh my!",
"(from the *"Wizard of OZ*")")
$)
// Print the 3 values, sort them, and print them again
and printAndSort(printfn, comp, x, y, z) be
$( print3(printfn, x, y, z) ; writes("*N")
sort3(comp, @x, @y, @z)
print3(printfn, x, y, z) ; writes("------*N")
$)
// Print 3 values given printing function
and print3(printfn, x, y, z) be
$( writes("X = ") ; printfn(x) ; wrch('*N')
writes("Y = ") ; printfn(y) ; wrch('*N')
writes("Z = ") ; printfn(z) ; wrch('*N')
$)
- Output:
X = 7444 Y = -12 Z = 0 X = -12 Y = 0 Z = 7444 ------ X = lions, tigers, and Y = bears, oh my! Z = (from the "Wizard of OZ") X = (from the "Wizard of OZ") Y = bears, oh my! Z = lions, tigers, and ------
C
Although C does not have a generic catch-all variable type, strings or arrays of characters can be used ( or misused ) to simulate the effect. Strings are often used to process arbitrarily large or small numbers which can't be represented by the C Standard Library. Strings are thus used for this task to accept whatever the user enters. Each entry is treated as a string and is scanned. If any one of them contains a single 'non-number' character, then the whole set is treated as a set of strings.
The first implementation is generic and can be used for any entries ( integer, floating point, strings). The second one is specific to the task and only sorts integers.
Generic Implementation
#include<string.h>
#include<stdlib.h>
#include<stdio.h>
#define MAX 3
int main()
{
char values[MAX][100],tempStr[100];
int i,j,isString=0;
double val[MAX],temp;
for(i=0;i<MAX;i++){
printf("Enter %d%s value : ",i+1,(i==0)?"st":((i==1)?"nd":"rd"));
fgets(values[i],100,stdin);
for(j=0;values[i][j]!=00;j++){
if(((values[i][j]<'0' || values[i][j]>'9') && (values[i][j]!='.' ||values[i][j]!='-'||values[i][j]!='+'))
||((values[i][j]=='.' ||values[i][j]=='-'||values[i][j]=='+')&&(values[i][j+1]<'0' || values[i][j+1]>'9')))
isString = 1;
}
}
if(isString==0){
for(i=0;i<MAX;i++)
val[i] = atof(values[i]);
}
for(i=0;i<MAX-1;i++){
for(j=i+1;j<MAX;j++){
if(isString==0 && val[i]>val[j]){
temp = val[j];
val[j] = val[i];
val[i] = temp;
}
else if(values[i][0]>values[j][0]){
strcpy(tempStr,values[j]);
strcpy(values[j],values[i]);
strcpy(values[i],tempStr);
}
}
}
for(i=0;i<MAX;i++)
isString==1?printf("%c = %s",'X'+i,values[i]):printf("%c = %lf",'X'+i,val[i]);
return 0;
}
The output shows three test cases, two as specified in the task, and one which mixes numbers and strings. The output is sorted considering all of them as strings in that case.
Enter 1st value : 77444 Enter 2nd value : -12 Enter 3rd value : 0 X = -12 Y = 0 Z = 77444 Enter 1st value : lions, tigers, and Enter 2nd value : bears, oh my! Enter 3rd value : (from the "Wizard of OZ") X = (from the "Wizard of OZ") Y = bears, oh my! Z = lions, tigers, and Enter 1st value : -12 Enter 2nd value : bears, oh my! Enter 3rd value : 77444 X = -12 Y = 77444 Z = bears, oh my!
Task Specific Implementation
#include<stdio.h>
int main()
{
int x = 77444,y=-12,z=0,temp;
printf("Before sorting :\nx = %d\ny = %d\nz = %d",x,y,z);
do{
temp = x;
if(temp > y){
x = y;
y = temp;
}
if(z < y){
temp = y;
y = z;
z = temp;
}
}while(x>y || y>z);
printf("\nAfter sorting :\nx = %d\ny = %d\nz = %d",x,y,z);
return 0;
}
Output :
Before sorting : x = 77444 y = -12 z = 0 After sorting : x = -12 y = 0 z = 77444
C#
using System;
public class Program
{
public static void Main()
{
(int x, int y, int z) = (77444, -12, 0);
//Sort directly:
if (x > y) (x, y) = (y, x);
if (x > z) (x, z) = (z, x);
if (y > z) (y, z) = (z, y);
Console.WriteLine((x, y, z));
var (a, b, c) = (
"lions, tigers, and",
"bears, oh my!",
"(from the 'Wizard of OZ')");
//Sort with generic method:
Sort(ref a, ref b, ref c);
Console.WriteLine((a, b, c));
}
public static void Sort<T>(ref T a, ref T b, ref T c)
where T : IComparable<T>
{
if (a.CompareTo(b) > 0) (a, b) = (b, a);
if (a.CompareTo(c) > 0) (a, c) = (c, a);
if (b.CompareTo(c) > 0) (b, c) = (c, b);
}
}
- Output:
(-12, 0, 77444) ((from the 'Wizard of OZ'), bears, oh my!, lions, tigers, and)
C++
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
template < class T >
void sort3( T& x, T& y, T& z) {
std::vector<T> v{x, y, z};
std::sort(v.begin(), v.end());
x = v[0]; y = v[1]; z = v[2];
}
int main() {
int xi = 77444, yi = -12, zi = 0;
sort3( xi, yi, zi );
std::cout << xi << "\n" << yi << "\n" << zi << "\n\n";
std::string xs, ys, zs;
xs = "lions, tigers, and";
ys = "bears, oh my!";
zs = "(from the \"Wizard of OZ\")";
sort3( xs, ys, zs );
std::cout << xs << "\n" << ys << "\n" << zs << "\n\n";
float xf = 11.3f, yf = -9.7f, zf = 11.17f;
sort3( xf, yf, zf );
std::cout << xf << "\n" << yf << "\n" << zf << "\n\n";
}
- Output:
-12 0 77444 (from the "Wizard of OZ") bears, oh my! lions, tigers, and -9.7 11.17 11.3
CLU
% Sort three variables.
% The variables must all be of the same type, and the type
% must implement the less-than comparator.
sort_three = proc [T: type] (x,y,z: T) returns (T,T,T)
where T has lt: proctype (T,T) returns (bool)
if y<x then x,y := y,x end
if z<y then y,z := z,y end
if y<x then x,y := y,z end
return(x,y,z)
end sort_three
% Test it out on three values, when also given a type and a
% formatter.
example = proc [T: type] (x,y,z: T, fmt: proctype (T) returns (string))
where T has lt: proctype (T,T) returns (bool)
po: stream := stream$primary_output()
% Print the variables
stream$putl(po, "x=" || fmt(x)
|| " y=" || fmt(y)
|| " z=" || fmt(z))
% Sort them
x,y,z := sort_three[T](x,y,z)
% Print them again
stream$putl(po, "x=" || fmt(x)
|| " y=" || fmt(y)
|| " z=" || fmt(z)
|| "\n")
end example
% And then we also need formatters, since those are not standardized
% such as '<' is.
fmt_real = proc (n: real) returns (string)
return(f_form(n,2,2))
end fmt_real
fmt_str = proc (s: string) returns (string)
return( "'" || s || "'" )
end fmt_str
% Test it out on values of each type
start_up = proc ()
example[int] (77444, -12, 0, int$unparse)
example[real] (11.3, -9.7, 11.17, fmt_real)
example[string] ("lions, tigers and", "bears, oh my!",
"(from the \"Wizard of Oz\")", fmt_str)
end start_up
- Output:
x=77444 y=-12 z=0 x=-12 y=0 z=77444 x=11.30 y=-9.70 z=11.17 x=-9.70 y=11.17 z=11.30 x='lions, tigers and' y='bears, oh my!' z='(from the "Wizard of Oz")' x='(from the "Wizard of Oz")' y='lions, tigers and' z='lions, tigers and'
COBOL
program-id. 3var.
data division.
working-storage section.
1 n binary pic 9(4).
1 num pic -(7)9.
1 a1 pic x(32) value "lions, tigers, and".
1 a2 pic x(32) value "bears, oh my!".
1 a3 pic x(32) value "(from the ""Wizard of OZ"")".
1 n1 pic x(8) value "77444".
1 n2 pic x(8) value "-12".
1 n3 pic x(8) value "0".
1 alpha-table.
2 alpha-entry occurs 3 pic x(32).
1 numeric-table.
2 numeric-entry occurs 3 pic s9(8).
1 filler value "x = y = z = ".
2 lead-in occurs 3 pic x(4).
procedure division.
begin.
move a1 to alpha-entry (1)
move a2 to alpha-entry (2)
move a3 to alpha-entry (3)
sort alpha-entry ascending alpha-entry
perform varying n from 1 by 1
until n > 3
display lead-in (n) alpha-entry (n)
end-perform
display space
compute numeric-entry (1) = function numval (n1)
compute numeric-entry (2) = function numval (n2)
compute numeric-entry (3) = function numval (n3)
sort numeric-entry ascending numeric-entry
perform varying n from 1 by 1
until n > 3
move numeric-entry (n) to num
display lead-in (n) num
end-perform
stop run
.
end program 3var.
- Output:
x = (from the "Wizard of OZ") y = bears, oh my! z = lions, tigers, and x = -12 y = 0 z = 77444
Cowgol
include "cowgol.coh";
# Sort 3 values
sub sort3(a: int32, b: int32, c: int32): (x: int32, y: int32, z: int32) is
sub sort2(a: int32, b: int32): (x: int32, y: int32) is
if a > b then
x := b;
y := a;
else
x := a;
y := b;
end if;
end sub;
x := a;
y := b;
z := c;
(x, y) := sort2(x, y);
(x, z) := sort2(x, z);
(y, z) := sort2(y, z);
end sub;
# Print 3 values
sub print3(a: int32, b: int32, c: int32) is
sub print1(a: int32) is
var buf: uint8[10];
[IToA(a, 10, &buf[0])] := 0;
print(&buf[0]);
print_char(' ');
end sub;
print1(a);
print1(b);
print1(c);
print_nl();
end sub;
var x: int32 := 77444;
var y: int32 := -12;
var z: int32 := 0;
# Print 3 values before sorting
print3(x, y, z);
# Sort 3 values
(x, y, z) := sort3(x, y, z);
# Print 3 values after sorting
print3(x, y, z);
- Output:
77444 -12 0 -12 0 77444
D
import std.stdio;
void main() {
driver(77444, -12, 0);
driver("lions, tigers, and", "bears, oh my!", "(from the \"Wizard of OZ\")");
}
void driver(T)(T x, T y, T z) {
writeln("BEFORE: x=[", x, "]; y=[", y, "]; z=[", z, "]");
sort3Var(x,y,z);
writeln("AFTER: x=[", x, "]; y=[", y, "]; z=[", z, "]");
}
void sort3Var(T)(ref T x, ref T y, ref T z)
out {
assert(x<=y);
assert(x<=z);
assert(y<=z);
}
body {
import std.algorithm : swap;
if (x < y) {
if (z < x) {
swap(x,z);
}
} else if (y < z) {
swap(x,y);
} else {
swap(x,z);
}
if (z<y) {
swap(y,z);
}
}
- Output:
BEFORE: x=[77444]; y=[-12]; z=[0] AFTER: x=[-12]; y=[0]; z=[77444] BEFORE: x=[lions, tigers, and]; y=[bears, oh my!]; z=[(from the "Wizard of OZ")] AFTER: x=[(from the "Wizard of OZ")]; y=[bears, oh my!]; z=[lions, tigers, and]
EasyLang
proc sort3 . a b c .
if a > c
swap a c
.
if b > c
swap b c
.
if a > b
swap a b
.
.
x = 77444
y = -12
z = 0
sort3 x y z
print x & " " & y & " " & z
#
proc sort3str . a$ b$ c$ .
if strcmp a$ c$ > 0
swap a$ c$
.
if strcmp b$ c$ > 0
swap b$ c$
.
if strcmp a$ b$ > 0
swap a$ b$
.
.
x$ = "lions, tigers, and"
y$ = "bears, oh my!"
z$ = "(from the \"Wizard of OZ\")"
sort3str x$ y$ z$
print x$
print y$
print z$
EDSAC order code
[Sort three variables, for Rosetta Code.
EDSAC, Initial Orders 2]
[---------------------------------------------------------------------------
Sorts three 35-bit variables x, y, x, stored at 0#V, 2#V, 4#V respectively.
Uses the algortihm:
if x > z then swap( x,z)
if y > z then swap( y,z)
if x > y then swap( x,y)
At most two swaps are carried out in any particular case.
----------------------------------------------------------------------------]
[Arrange the storage]
T47K P96F [M parameter: main routine]
T55K P128F [V parameter: variables to be sorted]
[Compressed form of library subroutine R2.
Reads integers at load time and is then overwritten.]
GKT20FVDL8FA40DUDTFI40FA40FS39FG@S2FG23FA5@T5@E4@E13Z
T#V [tell R2 where to store integers]
[EDIT: List of 35-bit integers separated by 'F', list terminated by '#TZ'.]
987654321F500000000F123456789#TZ
[Main routine]
E25K TM GK
[0] A4#V S#V [accumulator := z - x]
E8@ [skip the swap if x <= z]
TD [0D := z - x]
A#V U4#V [z := x]
AD [acc := old z]
T#V [x := old z]
[8] TF [clear acc]
A4#V S2#V [acc := z - y]
E17@ [skip the swap if y <= z]
TD [0D := z - y]
A2#V U4#V [z := y]
AD [acc := old z]
T2#V [y := old z]
[17] TF [clear acc]
A2#V S#V [acc := y - x]
E26@ [skip the swap if x <= y]
TD [0D := y - x]
A#V U2#V [y := x]
AD [acc := old y]
T#V [x := old y]
[26] ZF [halt the machine]
EZ [define entry point]
PF [acc = 0 on entry]
[end]
Elena
ELENA 6.x :
import extensions;
sortThree(ref object a, ref object b, ref object c)
{
if (a > b) { exchange(ref a, ref b) };
if (a > c) { exchange(ref a, ref c) };
if (b > c) { exchange(ref b, ref c) }
}
public program()
{
var x := 5;
var y := 1;
var z := 2;
var a := "lions, tigers, and";
var b := "bears, oh my!";
var c := "(from the 'Wizard of OZ')";
sortThree(ref x,ref y,ref z);
sortThree(ref a,ref b,ref c);
console.printLine(x,",",y,",",z);
console.printLine(a,",",b,",",c)
}
- Output:
1,2,5 (from the 'Wizard of OZ'),bears, oh my!,lions, tigers, and
Elixir
x = 'lions, tigers, and'
y = 'bears, oh my!'
z = '(from the "Wizard of OZ")'
[x, y, z] = Enum.sort([x, y, z])
IO.puts "x = #{x}\ny = #{y}\nz = #{z}\n"
x = 77444
y = -12
z = 0
[x, y, z] = Enum.sort([x, y, z])
IO.puts "x = #{x}\ny = #{y}\nz = #{z}"
- Output:
x = (from the "Wizard of OZ") y = bears, oh my! z = lions, tigers, and x = -12 y = 0 z = 77444
F#
let x = "lions, tigers, and"
let y = "bears, oh my!"
let z = """(from the "Wizard of OZ")"""
List.iter (printfn "%s") (List.sort [x;y;z])
- Output:
(from the "Wizard of OZ") bears, oh my! lions, tigers, and
Factor
USING: arrays io kernel prettyprint sequences sorting ;
IN: rosetta-code.sort-three
: sort3 ( b c a -- a b c ) 3array natural-sort first3 ;
"lions, tigers, and"
"bears, oh my!"
"(from the \"Wizard of OZ\")"
sort3 [ print ] tri@
77444 -12 0 sort3 [ . ] tri@
- Output:
(from the "Wizard of OZ") bears, oh my! lions, tigers, and -12 0 77444
FALSE
FALSE supports neither floating point numbers nor strings.
{ [s]waps two variables. (varref; varref) → () }
[
b: { loads the value at the top of the stack into b }
a: { loads the value at the top of the stack into a }
a;; t: { loads the value stored in the variable stored in a (hence the double dereference) into t }
b;; a;: { loads the value stored in the variable stored in b into the variable stored in a }
t; b;: { loads the value stored in t into the variable stored in b }
]s:
{ [p]rints the three variables. }
[
"X = " x;. 10,
"Y = " y;. 10,
"Z = " z;. 10,
]p:
77444 x:
12_ y:
0 z:
p;!
{ if x > y, swap x and y }
x;y;> [xys;!] ?
{ if y > z, swap y and z }
y;z;> [yzs;!] ?
{ if x > y, swap x and y }
x;y;> [xys;!] ?
"After sorting:
"
p;!
- Output:
X = 77444 Y = -12 Z = 0 After sorting: X = -12 Y = 0 Z = 77444
FreeBASIC
Shows the use of macros, which are type-agnostic (though you cannot mix string and numerical types).
#macro sort_three( x, y, z )
if x>y then swap x, y
if y>z then swap y, z
if x>y then swap x, y
#endmacro
'demonstrate this for strings
dim as string x = "lions, tigers, and"
dim as string y = "bears, oh my!"
dim as string z = "(from the ""Wizard of OZ"")"
sort_three(x,y,z)
print x
print y
print z : print
'demonstrate this for signed integers
dim as integer a = 77444
dim as integer b = -12
dim as integer c = 0
sort_three(a,b,c)
print a
print b
print c
- Output:
(from the "Wizard of OZ")bears, oh my! lions, tigers, and
-12
077444
Forth
Integers
In GNU Forth the machine's integers are the default data type.
It is straightforward to sort these on the Forth Data Stack.
Note:
Assigning the values to variables is simple however unless
storage in variables was needed to retain the values, they would
typically be used directly from the stack by a subsequent operation in the
program.
\ sort 3 integers
VARIABLE X VARIABLE Y VARIABLE Z
: VARS@ ( --- n n n) X @ Y @ Z @ ; \ read variables
: VARS! ( n n n -- ) Z ! Y ! X ! ; \ store variables
: ?SWAP ( a b -- a b) \ conditional swap
2DUP < IF SWAP THEN ;
: SORT3INTS ( a b c -- c b a) ?SWAP >R ?SWAP R> ?SWAP ;
Testing is done using the Forth console using '?' to view VARIABLE contents
ok 77000 -12 0 VARS! ok X ? 77000 ok Y ? -12 ok Z ? 0 ok VARS@ SORT3INTS VARS! ok X ? 77000 ok Y ? 0 ok Z ? -12 ok
Strings
Strings require extending the language but the primitives needed are part of ANS/ISO Forth.
DECIMAL
: BUFFER: ( n -- ) CREATE ALLOT ;
64 BUFFER: X
64 BUFFER: Y
64 BUFFER: Z
: S' ( <text> ) [CHAR] ' PARSE ;
S' (from the "Wizard of OZ")' X PLACE
S' bears, oh my!' Y PLACE
S' lions, tigers, and' Z PLACE
\ counted string compare less than
: <S ( caddr caddr -- caddr caddr flag)
COUNT ROT COUNT COMPARE 1 = ;
: ?SWAPSTR ( caddr caddr -- caddr caddr) \ conditional string swap
2DUP <S IF SWAP THEN ;
\ sort on stack as done for integers
: SORT3STRINGS ?SWAPSTR >R ?SWAPSTR R> ?SWAPSTR ;
\ non-destructive print 3 counted-strings from data stack
: .STRS ( caddr1 caddr2 caddr3 -- caddr1 caddr2 caddr3) \ order is dependant
3 0 DO ROT DUP CR COUNT TYPE LOOP ;
With these extensions we can do the same testing at the Forth console and examine the string order with '.STRS'.
ok X Y Z ok .S <3> 2142061672 2142061760 2142061848 ok .STRS (from the "Wizard of OZ") bears, oh my! lions, tigers, and ok SORT3STRINGS ok .S <3> 2142061848 2142061760 2142061672 ok .STRS lions, tigers, and bears, oh my! (from the "Wizard of OZ") ok
Fortran
Fortran does not offer a multi-mode facility whereby a variable can be the union of various basic types such as integer or floating-point or character. The EQUIVALENCE statement can cause three such different variables to be placed at the same storage location or indeed, because parameter type-checking is rarely performed by a Fortran compiler (especially with routines compiled separately) it is often possible to pass a floating-point variable to a subroutine expecting an integer, and so forth. Leaving aside questions of storage size mismatch (as when a subroutine stores a sixty-four bit double-precision value into a parameter it had been supplied as a sixteen-bit integer, say) the bit patterns of disparate types will rarely involve a useful ordering. For example, an eight-byte floating-point variable could contain the bit pattern of "Hi There" but the numerical value that will manifest will not likely be useful in sorting text. Though it could be. Imagine having a collection of eight-character codes that is to be searched frequently by a binary chop method. If the actual ordering is unimportant, they could be both sorted and searched as REAL*8 variables, dealing with all eight characters at one blow. However, given the modern floating-point usage of Not-a-Number and the like, it would probably be safer to work with integer variables so that every bit pattern would be distinct. Alas, on the B6700, the high-order bit of its 48-bit word was not used in arithmetic so if an eight-bit character code were to be placed in the high-order eight bits, some character codes would not be distinguished.
It is possible to use floating-point variables to store integer values and their ordering will be sensible, but the bit patterns of integer and floating-point values are usually very different. Again, a subroutine that is supplied integer variables (even of the right size) but which works with floating-point variables (or vice-versa) will not produce a sensible ordering. Except perhaps on a B6700 where integer values were represented as floating-point numbers with no fractional part. Operations such as add, subtract, and multiply proceeded as normal while divide discarded any resulting fractional part.
The most flexible type of variable is text, as the text can represent any type of value - but as text, not as a proper number. The ordering resulting from numbers represented as text will be very dependent on their format. This is discussed in Natural_sorting for example.
The example source uses F90 mainly to enable the contained routine SWAPC though it could be made into a separate subroutine. Further F90 facilities would allow the definition of a "generic" SORT3 routine, with a lot of syntax that would enable a SORT3I2, SORT3I4, SORT3F4, etc. routines for INTEGER*2, INTEGER*4, REAL*4, etc. to be selected for each case. A suitable pre-processor scheme could perhaps generate these variations, but alas, it is not standard. The resulting SORT3 routine could be invoked for sets of parameters of any of the types prepared for, but it will only appear to be one routine working with different types of parameters; in fact different actual routines would be invoked by the compiler selecting according to the type of the actual parameters.
There would be similar requirements for a SWAP routine for each type of parameter, for alas, Fortran does not define a SWAP statement. The temporary variable needed for the SWAP process is defined rather intimidatingly as having the size of the largest of the three parameters; prior to F90 variables defined in a routine could only have a size defined at compile time, which would have to be "surely big enough". Rather than have this redefined for each invocation of SWAPC (where it would be the larger of the two parameters) it is defined once in SORT3. However, all three parameters should be the same size, or risk truncation. Using a great deal more syntax (or, as standardised in F2003) it is possible to have character variables be resized on each assignment to them to accommodate the length of text being assigned.
One could make rather more use of the facilities of F90 and define a compound data type, such as
TYPE(MONGREL)
INTEGER TYPEIS
INTEGER VI
REAL VF
CHARACTER*(enuff) VC
...etc...
END TYPE MONGREL
TYPE (MONGREL) DOG
So that DOG.TYPEIS would indicate which component to access. Still further ploys would enable storage to be allocated only for the type currently in use, especially for CHARACTER variables, and via a great deal more syntax defining how to perform operations such as .GT. and the like, MONGREL type variables can be used in expressions involving such operators just as can variables of the basic types. This sort of approach is demonstrated in Arithmetic/Rational#Fortran, but otherwise, every reference to a MONGREL will involve some sort of CASE statement to select the appropriate usage, hopefully of related types only. Serious computation with such MONGREL variables surely will not be speedy and thus would be un-Fortrannish. What to do when a text string meets a complex number remains obscure - convert the number to a text (but, what format?), does the text represent a number? And what type results from such miscegnation?
Routines that modify their parameters should not be invoked with constants (or text literals) as such parameters... Some systems allow constants to be in protected storage, and if so, an attempt to modify such storage will produce a run-time error. Otherwise, it all depends on how constants are passed as parameters. If a temporary storage item is loaded with the desired value and the address of that scratch variable is passed, then disaster will be averted - though good results may not be produced.
For convenience in setting up the two examples, an array is used to hold the test data. The subroutine is not invoked with an array parameter, it is invoked with three separate elements of the array. The DATA statement initialising the array looks to be the transpose of the desired ordering, because of the way Fortran orders elements in storage.
SUBROUTINE SORT3(X,Y,Z) !Perpetrate a bubblesort in-line.
CHARACTER*(*) X,Y,Z !Just three to rearrange.
CHARACTER*(MAX(LEN(X),LEN(Y),LEN(Z))) T !Really, they should all be the same length.
IF (X.GT.Y) CALL SWAPC(X,Y) !The first pass: for i:=2:3 do if a(i - 1) > a(i) swap
IF (Y.GT.Z) CALL SWAPC(Y,Z) !The second test of the first pass.
IF (X.GT.Y) CALL SWAPC(X,Y) !The second pass: for i:=2:2...
CONTAINS !Alas, Fortran does not offer a SWAP statement.
SUBROUTINE SWAPC(A,B) !So, one must be devised for each case.
CHARACTER*(*) A,B !To have their content swapped.
T = A !Ccpy the first to a safe space.
A = B !Copy the second on to the first.
B = T !Copy what had been first to the second.
END SUBROUTINE SWAPC !One of these will be needed for each type of datum.
END SUBROUTINE SORT3 !No attempt is made to stop early, as for already-ordered data.
PROGRAM POKE
CHARACTER*28 XYZ(3,2) !Encompass the two examples.
DATA XYZ/ !Storage order is "column-major".
1 'lions, tigers, and','bears, oh my!','(from the "Wizard of OZ")', !So (1,1), (2,1), (3,1)
2 '77444',' -12',' 0'/ !So this looks like a transposed array. But (1,2), (2,2), (3,2)
INTEGER I !A stepper for the loop.
DO I = 1,2 !Two examples.
WRITE (6,66) "Supplied: ", XYZ(1:3,I) !As given.
66 FORMAT (A12,3(" >",A,"<")) !Show as >text< for clarity.
CALL SORT3(XYZ(1,I),XYZ(2,I),XYZ(3,I)) !Three separate variables, that happen to be in an array.
WRITE (6,66) "Sorted, ? ", XYZ(1:3,I) !The result.
END DO !On to the next example.
END !Nothing much.
Output: the texts showing numbers appear in text order, not the order of their numbers. Incidentally, not everything is done in ASCII. The EBCDIC ordering is different.
Supplied: >lions, tigers, and < >bears, oh my! < >(from the "Wizard of OZ") < Sorted, ? >(from the "Wizard of OZ") < >bears, oh my! < >lions, tigers, and < Supplied: >77444 < > -12 < > 0 < Sorted, ? > 0 < > -12 < >77444 <
Fōrmulæ
Fōrmulæ programs are not textual, visualization/edition of programs is done showing/manipulating structures but not text. Moreover, there can be multiple visual representations of the same program. Even though it is possible to have textual representation —i.e. XML, JSON— they are intended for storage and transfer purposes more than visualization and edition.
Programs in Fōrmulæ are created/edited online in its website.
In this page you can see and run the program(s) related to this task and their results. You can also change either the programs or the parameters they are called with, for experimentation, but remember that these programs were created with the main purpose of showing a clear solution of the task, and they generally lack any kind of validation.
Solution
Test case 1
Test case 2
Free Pascal
The FPC (FreePascal Compiler) adopted Delphi’s generics scheme. It works in the {$mode objFPC} and {$mode Delphi} compiler compatibility modes, the former requiring the keywords generic/specialize.
{$mode objFPC}
generic procedure sort<T>(var X, Y: T);
procedure swap;
var
Z: T;
begin
Z := X;
X := Y;
Y := Z
end;
begin
if X > Y then
begin
swap
end
end;
generic procedure sort<T>(var X, Y, Z: T);
begin
specialize sort<T>(X, Y);
specialize sort<T>(X, Z);
specialize sort<T>(Y, Z)
end;
generic procedure print<T>(const X, Y, Z: T);
begin
writeLn('X = ', X);
writeLn('Y = ', Y);
writeLn('Z = ', Z)
end;
{ === MAIN ============================================================= }
var
A, B, C: string;
I, J, K: integer;
P, Q, R: real;
begin
A := 'lions, tigers, and';
B := 'bears, oh my!';
C := '(from the "Wizard of OZ")';
specialize sort<string>(A, B, C);
specialize print<string>(A, B, C);
writeLn;
I := 77444;
J := -12;
K := 0;
specialize sort<integer>(I, J, K);
specialize print<integer>(I, J, K);
writeLn;
P := 12.34;
Q := -56.78;
R := 9.01;
specialize sort<real>(P, Q, R);
specialize print<real>(P, Q, R)
end.
- Output:
X = (from the "Wizard of OZ") Y = bears, oh my! Z = lions, tigers, and X = -12 Y = 0 Z = 77444 X = -5.6780000000000001E+001 Y = 9.0099999999999998E+000 Z = 1.2340000000000000E+001
Frink
The following sorts the values in the variables x, y, and z and sets the sorted values back to the variables.
x = 77444
y = -12
z = 0
[x,y,z] = sort[[x,y,z]]
println["x = $x"]
println["y = $y"]
println["z = $z"]
- Output:
x = -12 y = 0 z = 77444
Go
There are ways of doing this task in a generic way in Go but they are a bit cumbersome and it would not be idiomatic. Shown here then are solutions coded specifically to the string and integer types of the task test cases. Solutions would be very similar for any of the other comparable Go types such as float64.
package main
import (
"fmt"
"log"
"sort"
)
var (
stringsIn = []string{
`lions, tigers, and`,
`bears, oh my!`,
`(from the "Wizard of OZ")`}
intsIn = []int{77444, -12, 0}
)
func main() {
{
// initialize three vars
x, y, z := stringsIn[0], stringsIn[1], stringsIn[2]
// I. Task suggested technique, move values to array (slice).
// It's consise and relies on library code.
s := []string{x, y, z}
sort.Strings(s)
x, y, z = s[0], s[1], s[2]
// validate
if x > y || y > z {
log.Fatal()
}
// II. Likely fastest technique, minimizing tests and data movement.
// Least consise though, hardest to understand, and most chance to make
// a coding mistake.
x, y, z = stringsIn[0], stringsIn[1], stringsIn[2] // (initialize)
if x < y {
switch {
case y < z:
case x < z:
y, z = z, y
default:
x, y, z = z, x, y
}
} else {
switch {
case x < z:
x, y = y, x
case z < y:
x, z = z, x
default:
x, y, z = y, z, x
}
}
if x > y || y > z { // (validate)
log.Fatal()
}
// III. A little more consise than II, easier to understand, almost
// as fast.
x, y, z = stringsIn[0], stringsIn[1], stringsIn[2] // (initialize)
if x > y {
x, y = y, x
}
if y > z {
y, z = z, y
}
if x > y {
x, y = y, x
}
if x > y || y > z { // (validate)
log.Fatal()
}
fmt.Println("sorted strings:")
fmt.Println(" ", x)
fmt.Println(" ", y)
fmt.Println(" ", z)
fmt.Println("original data:")
fmt.Println(" ", stringsIn[0])
fmt.Println(" ", stringsIn[1])
fmt.Println(" ", stringsIn[2])
}
// same techniques, with integer test case
{
// task suggested technique
x, y, z := intsIn[0], intsIn[1], intsIn[2] // (initialize)
s := []int{x, y, z}
sort.Ints(s)
x, y, z = s[0], s[1], s[2]
if x > y || y > z { // (validate)
log.Fatal()
}
// minimizing data movement
x, y, z = intsIn[0], intsIn[1], intsIn[2] // (initialize)
if x < y {
switch {
case y < z:
case x < z:
y, z = z, y
default:
x, y, z = z, x, y
}
} else {
switch {
case x < z:
x, y = y, x
case z < y:
x, z = z, x
default:
x, y, z = y, z, x
}
}
if x > y || y > z { // (validate)
log.Fatal()
}
// three swaps
x, y, z = intsIn[0], intsIn[1], intsIn[2] // (initialize)
if x > y {
x, y = y, x
}
if y > z {
y, z = z, y
}
if x > y {
x, y = y, x
}
if x > y || y > z { // (validate)
log.Fatal()
}
fmt.Println("sorted ints:", x, y, z)
fmt.Println("original data:", intsIn)
}
// To put any of these techniques in a function, a function could just
// take three values and return them sorted.
{
sort3 := func(x, y, z int) (int, int, int) {
if x > y {
x, y = y, x
}
if y > z {
y, z = z, y
}
if x > y {
x, y = y, x
}
return x, y, z
}
x, y, z := intsIn[0], intsIn[1], intsIn[2] // (initialize)
x, y, z = sort3(x, y, z)
if x > y || y > z { // (validate)
log.Fatal()
}
}
// Alternatively, a function could take pointers
{
sort3 := func(x, y, z *int) {
if *x > *y {
*x, *y = *y, *x
}
if *y > *z {
*y, *z = *z, *y
}
if *x > *y {
*x, *y = *y, *x
}
}
x, y, z := intsIn[0], intsIn[1], intsIn[2] // (initialize)
sort3(&x, &y, &z)
if x > y || y > z { // (validate)
log.Fatal()
}
}
}
- Output:
sorted strings: (from the "Wizard of OZ") bears, oh my! lions, tigers, and original data: lions, tigers, and bears, oh my! (from the "Wizard of OZ") sorted ints: -12 0 77444 original data: [77444 -12 0]
Haskell
Fortunately, Haskell prevents us from doing this kind of thing. It does makes flexible use of bound names, including names for function arguments, but it also protects us from the heavy costs to productivity and reliability that are inevitably imposed by mutating the meaning of bound names at run-time.
Although mutation is not on the menu, parameterised types do allow us to define polymorphic functions which can, for example, be applied both to lists of strings and also to lists of integers or lists of floats. The following functions work with triples of any type for which the <= or compare functions are defined – in other words, any type for which an instance of the Ord class is defined.
import Data.List (sort)
sortedTriple
:: Ord a
=> (a, a, a) -> (a, a, a)
sortedTriple (x, y, z) =
let [a, b, c] = sort [x, y, z]
in (a, b, c)
sortedListfromTriple
:: Ord a
=> (a, a, a) -> [a]
sortedListfromTriple (x, y, z) = sort [x, y, z]
-- TEST ----------------------------------------------------------------------
main :: IO ()
main = do
print $
sortedTriple
("lions, tigers, and", "bears, oh my!", "(from the \"Wizard of OZ\")")
print $
sortedListfromTriple
("lions, tigers, and", "bears, oh my!", "(from the \"Wizard of OZ\")")
print $ sortedTriple (77444, -12, 0)
print $ sortedListfromTriple (77444, -12, 0)
- Output:
("(from the \"Wizard of OZ\")","bears, oh my!","lions, tigers, and") ["(from the \"Wizard of OZ\")","bears, oh my!","lions, tigers, and"] (-12,0,77444) [-12,0,77444]
IS-BASIC
100 LET X=77444:LET Y=-12:LET Z=0
110 PRINT X;Y;Z
120 CALL SHORT(X,Y,Z)
130 PRINT X;Y;Z
140 DEF SHORT(REF A,REF B,REF C)
150 IF A>B THEN LET T=A:LET A=B:LET B=T
160 IF B>C THEN LET T=B:LET B=C:LET C=T
170 IF A>B THEN LET T=A:LET A=B:LET B=T
180 END DEF
- Output:
77444 -12 0 -12 0 77444
J
Note that this is extremely bad form, and you will stumble over why it is bad form if you try using it in any useful implementation:
x =: 'lions, tigers, and'
y =: 'bears, oh my!'
z =: '(from the "Wizard of OZ")'
'x y z'=: /:~".'x;y;<z'
x
(from the "Wizard of OZ")
y
bears, oh my!
z
lions, tigers, and
x =: 77444
y =: -12
z =: 0
'x y z'=: /:~".'x;y;<z'
x
_12
y
0
z
77444
Java
import java.util.Comparator;
import java.util.stream.Stream;
class Box {
public int weightKg;
Box(final int weightKg) {
this.weightKg = weightKg;
}
}
public class Sort3Vars {
public static void main(String... args) {
int iA = 21;
int iB = 11;
int iC = 82;
int[] sortedInt = Stream.of(iA, iB, iC).sorted().mapToInt(Integer::intValue).toArray();
iA = sortedInt[0];
iB = sortedInt[1];
iC = sortedInt[2];
System.out.printf("Sorted values: %d %d %d%n", iA, iB, iC);
String sA = "s21";
String sB = "s11";
String sC = "s82";
Object[] sortedStr = Stream.of(sA, sB, sC).sorted().toArray();
sA = (String) sortedStr[0];
sB = (String) sortedStr[1];
sC = (String) sortedStr[2];
System.out.printf("Sorted values: %s %s %s%n", sA, sB, sC);
Box bA = new Box(200);
Box bB = new Box(12);
Box bC = new Box(143);
// Provides a comparator for Box instances
Object[] sortedBox = Stream.of(bA, bB, bC).sorted(Comparator.comparingInt(a -> a.weightKg)).toArray();
bA = (Box) sortedBox[0];
bB = (Box) sortedBox[1];
bC = (Box) sortedBox[2];
System.out.printf("Sorted Boxes: %dKg %dKg %dKg%n", bA.weightKg, bB.weightKg, bC.weightKg);
}
}
- Output:
Sorted values: 11 21 82 Sorted values: s11 s21 s82 Sorted Boxes: 12Kg 143Kg 200Kg
JavaScript
const printThree = (note, [a, b, c], [a1, b1, c1]) => {
console.log(`${note}
${a} is: ${a1}
${b} is: ${b1}
${c} is: ${c1}
`);
};
const sortThree = () => {
let a = 'lions, tigers, and';
let b = 'bears, oh my!';
let c = '(from the "Wizard of OZ")';
printThree('Before Sorting', ['a', 'b', 'c'], [a, b, c]);
[a, b, c] = [a, b, c].sort();
printThree('After Sorting', ['a', 'b', 'c'], [a, b, c]);
let x = 77444;
let y = -12;
let z = 0;
printThree('Before Sorting', ['x', 'y', 'z'], [x, y, z]);
[x, y, z] = [x, y, z].sort();
printThree('After Sorting', ['x', 'y', 'z'], [x, y, z]);
};
sortThree();
- Output:
Before Sorting a is: lions, tigers, and b is: bears, oh my! c is: (from the "Wizard of OZ") After Sorting a is: (from the "Wizard of OZ") b is: bears, oh my! c is: lions, tigers, and Before Sorting x is: 77444 y is: -12 z is: 0 After Sorting x is: -12 y is: 0 z is: 77444
jq
In this entry, we shall use a JSON object to represent a set of variables and their bindings. jq supports this interpretation: for example, the assignment operator '=' can be used to set the value associated with a key, as in `.x = 0`. jq also allows JSON objects to be specified in a jq program using a JSON-like syntax, e.g. {x: 1}, as illustrated below.
The sorting function defined here is completely generic with respect to the number of variables and the types of their values. For brevity, however, we will only use the required examples.
def example1:
{x: "lions, tigers, and",
y: "bears, oh my",
z: "(from the \"Wizard of OZ\")"
};
def example2:
{x: 77444,
y: -12,
z: 0
};
The following sorting function will accept an arbitrary JSON object:
def sortVariables:
keys_unsorted as $keys
| ([.[]] | sort) as $values
| reduce range(0; $keys|length) as $i ({}; .[$keys[$i]] = ($values[$i]) ) ;
Examples:
example1 | sortVariables
- Output:
{ "x": "(from the \"Wizard of OZ\")", "y": "bears, oh my", "z": "lions, tigers, and" }
example2 | sortVariables
- Output:
{
"x": -12, "y": 0, "z": 77444}
Jsish
#!/usr/bin/env jsish
/* Sort three variables, in Jsish. semi-colon start/end for unit test echo */
var x = 'lions, tigers, and';
var y = 'bears, oh my!';
var z = '(from the "Wizard of OZ")';
var arr = [x,y,z];
arr = arr.sort();
;'As strings, before:';
;x;
;y;
;z;
x = arr.shift();
y = arr.shift();
z = arr.shift();
;'x,y,z after:';
;x;
;y;
;z;
x = 77444;
y = -12;
z = 0;
arr = [x,y,z];
arr = arr.sort();
;'As numbers before:';
;x;
;y;
;z;
x = arr.shift();
y = arr.shift();
z = arr.shift();
;'x,y,z after:';
;x;
;y;
;z;
;'Mixed, integer, float, string';
x = 3.14159;
y = 2;
z = '1 string';
;x;
;y;
;z;
arr = [x,y,z].sort();
x = arr.shift(); y = arr.shift(); z = arr.shift();
;'x,y,z after:';
;x;
;y;
;z;
/*
=!EXPECTSTART!=
'As strings, before:'
x ==> lions, tigers, and
y ==> bears, oh my!
z ==> (from the "Wizard of OZ")
'x,y,z after:'
x ==> (from the "Wizard of OZ")
y ==> bears, oh my!
z ==> lions, tigers, and
'As numbers before:'
x ==> 77444
y ==> -12
z ==> 0
'x,y,z after:'
x ==> -12
y ==> 0
z ==> 77444
'Mixed, integer, float, string'
x ==> 3.14159
y ==> 2
z ==> 1 string
'x,y,z after:'
x ==> 2
y ==> 3.14159
z ==> 1 string
=!EXPECTEND!=
*/
- Output:
prompt$ jsish --U sortThree.jsi 'As strings, before:' x ==> lions, tigers, and y ==> bears, oh my! z ==> (from the "Wizard of OZ") 'x,y,z after:' x ==> (from the "Wizard of OZ") y ==> bears, oh my! z ==> lions, tigers, and 'As numbers before:' x ==> 77444 y ==> -12 z ==> 0 'x,y,z after:' x ==> -12 y ==> 0 z ==> 77444 'Mixed, integer, float, string' x ==> 3.14159 y ==> 2 z ==> 1 string 'x,y,z after:' x ==> 2 y ==> 3.14159 z ==> 1 string prompt$ jsish -u sortThree.jsi [PASS] sortThree.jsi
Julia
# v0.6
a, b, c = "lions, tigers, and", "bears, oh my!", "(from the \"Wizard of OZ\")"
a, b, c = sort([a, b, c])
@show a b c
a, b, c = 77444, -12, 0
a, b, c = sort([a, b, c])
@show a b c
- Output:
a = "(from the \"Wizard of OZ\")" b = "bears, oh my!" c = "lions, tigers, and" a = -12 b = 0 c = 77444
Kotlin
Kotlin's standard library contains a sort() function which can sort any generic array whose element type has a defined ordering between its instances. This includes strings, integers and floats examples of which are shown below:
// version 1.1.2
inline fun <reified T : Comparable<T>> sortThree(x: T, y: T, z: T): Triple<T, T, T> {
val a = arrayOf(x, y, z)
a.sort()
return Triple(a[0], a[1], a[2])
}
fun <T> printThree(x: T, y: T, z: T) = println("x = $x\ny = $y\nz = $z\n")
fun main(args: Array<String>) {
var x = "lions, tigers, and"
var y = "bears, oh my!"
var z = """(from the "Wizard of OZ")"""
val t = sortThree(x, y, z)
x = t.first
y = t.second
z = t.third
printThree(x, y, z)
var x2 = 77444
var y2 = -12
var z2 = 0
val t2 = sortThree(x2, y2, z2)
x2 = t2.first
y2 = t2.second
z2 = t2.third
printThree(x2, y2, z2)
var x3 = 174.5
var y3 = -62.5
var z3 = 41.7
val t3 = sortThree(x3, y3, z3)
x3 = t3.first
y3 = t3.second
z3 = t3.third
printThree(x3, y3, z3)
}
- Output:
x = (from the "Wizard of OZ") y = bears, oh my! z = lions, tigers, and x = -12 y = 0 z = 77444 x = -62.5 y = 41.7 z = 174.5
Ksh
#!/bin/ksh
# Sort three variables that may contain any value (numbers and/or literals)
# # Variables:
#
xl='lions, tigers, and'
yl='bears, oh my!'
zl='(from the "Wizard of OZ")'
typeset -i xn=77444
typeset -F yn=-12.0
typeset -i zn=0
# # Functions:
#
# # Function _intoarray(x, y, z, arr) - put 3 variables into arr[]
#
function _intoarray {
typeset _x ; nameref _x="$1"
typeset _y ; nameref _y="$2"
typeset _z ; nameref _z="$3"
typeset _arr ; nameref _arr="$4"
_arr=( "${_x}" "${_y}" "${_z}" )
}
# # Function _arraysort(arr) - return sorted array (any type of elements)
#
function _arraysort {
typeset _arr ; nameref _arr="$1"
typeset _i _j ; integer _i _j
_sorttype _arr
case $? in
0) # Literal sort
for (( _i=1; _i<${#_arr[*]}; _i++ )); do
_val="${_arr[_i]}"
(( _j = _i - 1 ))
while (( _j>=0 )) && [[ "${_arr[_j]}" > "${_val}" ]]; do
_arr[_j+1]="${_arr[_j]}"
(( _j-- ))
done
_arr[_j+1]="${_val}"
done
;;
1) # Numeric sort
for (( _i=1; _i<${#_arr[*]}; _i++ )); do
_val=${_arr[_i]}
(( _j = _i - 1 ))
while (( _j>=0 && _arr[_j]>_val )); do
_arr[_j+1]=${_arr[_j]}
(( _j-- ))
done
_arr[_j+1]=${_val}
done
;;
esac
}
# # Function _sorttype(_arr) - return 0 = Literal sort; 1 = Numeric sort
#
function _sorttype {
typeset _arr ; nameref _arr="$1"
typeset _i ; integer _i
for ((_i=0; _i<${#_arr[*]}; _i++)); do
[[ ${_arr[_i]} != *(\-)+(\d)*(\.)*(\d) ]] && return 0
done
return 1
}
# # Function _outofarray(x, y, z, arr) - Put array elements into x, y, z
#
function _outofarray {
typeset _x ; nameref _x="$1"
typeset _y ; nameref _y="$2"
typeset _z ; nameref _z="$3"
typeset _arr ; nameref _arr="$4"
_x="${_arr[0]}"
_y="${_arr[1]}"
_z="${_arr[2]}"
}
######
# main #
######
unset x y z
printf "Numeric Variables:\n%s\n%s\n%s\n\n" "${xn}" "${yn}" "${zn}"
typeset -a arrayn
_intoarray xn yn zn arrayn
_arraysort arrayn
_outofarray x y z arrayn
printf "Sorted Variables:\n%s\n%s\n%s\n\n" "${x}" "${y}" "${z}"
unset x y z
printf "Literal Variables:\n%s\n%s\n%s\n\n" "${xl}" "${yl}" "${zl}"
typeset -a arrayl
_intoarray xl yl zl arrayl
_arraysort arrayl
_outofarray x y z arrayl
printf "Sorted Variables:\n%s\n%s\n%s\n\n" "${x}" "${y}" "${z}"
- Output:
Numeric Variables: 77444 -12.0000000000000 0
Sorted Variables: -12.0000000000000 0 77444
Literal Variables: lions, tigers, and bears, oh my! (from the "Wizard of OZ")
Sorted Variables: bears, oh my! (from the "Wizard of OZ")
lions, tigers, and
Little Man Computer
The LMC in its original form supports only integers in the range 0..999. So the numbers in the task have been changed here from 77444, -12, 0 to 774, 0, 12.
// Little Man Computer
// Sort x, y, z, in ascending order
// Based on a sorting network:
// if x > z then swap( x, z)
// if x > y then swap( x, y)
// if y > z then swap( y, z)
// with the addition that if the 2nd swap is executed
// then the 3rd comparison is not needed.
// Read numbers x, y, z, and display in their original order
INP
STA x
OUT
INP
STA y
OUT
INP
STA z
OUT
// Sort so that x <= y <= z, and display in new order
LDA z
SUB x
BRP label1
LDA x
STA t
LDA z
STA x
LDA t
STA z
label1 LDA y
SUB x
BRP label2
LDA x
STA t
LDA y
STA x
LDA t
STA y
BRA sorted // added to the sorting network
label2 LDA z
SUB y
BRP sorted
LDA y
STA t
LDA z
STA y
LDA t
STA z
sorted LDA x
OUT
LDA y
OUT
LDA z
OUT
HLT
x DAT
y DAT
z DAT
t DAT
// end
- Output:
744 0 12 0 12 744
Lua
Essentially the same as the example algorithm except that the function is variadic. Sorting is done by the in-built table.sort and copying the unknown number of variables in and out of the table is made simple by the (...) in the parameter list and the unpack function respectively.
function variadicSort (...)
local t = {}
for _, x in pairs{...} do
table.insert(t, x)
end
table.sort(t)
return unpack(t)
end
local testCases = {
{ x = 'lions, tigers, and',
y = 'bears, oh my!',
z = '(from the "Wizard of OZ")'
},
{ x = 77444,
y = -12,
z = 0
}
}
for i, case in ipairs(testCases) do
x, y, z = variadicSort(case.x, case.y, case.z)
print("\nCase " .. i)
print("\tx = " .. x)
print("\ty = " .. y)
print("\tz = " .. z)
end
- Output:
Case 1 x = (from the "Wizard of OZ") y = bears, oh my! z = lions, tigers, and Case 2 x = -12 y = 0 z = 77444
M2000 Interpreter
Variables in M2000 are type of Variant, Interpreter use name type ($) to use proper expression parser something as string. In this example we pass reference from numeric to string identifiers, but data under never moved, so we can read the type, and then we can make second reference to numeric names, and then we use the proper expression parser.
Swap statement swap variants (data), not references, and always swap 16bytes. All arrays are variant type, so we can swap array item with any variable (but names must be the same type - strings or numeric both)
Subs can be found from parent context, but executed like they are in current context. A sub has scope in Module, so can call any sub including itself. For optimization , Interpreter mark in temporary list the sub positions, at the first call. Modules and Functions have a special list, where included at definition time, end excluded when parent exit.
Module Sort3 {
Let X=77744, Y=-12, Z=0
Let X$ = "lions, tigers, and", Y$ = "bears, oh my!", Z$ = {(from the "Wizard of OZ")}
\\ & use for by reference pass
Module SortSome (&X$, &Y$, &Z$){
If Type$(X$)<>"String" Then {
Link X$,Y$, Z$ to X,Y,Z
Print3()
If Y>Z then Swap Y, Z ' both numeric in Swap
If X>Z then Swap X, Z
If X>Y then Swap X, Y
Print3()
} Else {
Print3Str()
If Y$>Z$ then Swap Y$, Z$ ' both strings in Swap
If X$>Z$ then Swap X$, Z$
If X$>Y$ then Swap X$, Y$
Print3Str()
}
}
SortSome &X, &Y, &Z
SortSome &X$, &Y$, &Z$
Sub Print3()
\\ double ,, used to insert a New Line
Print "X=",X,,"Y=",Y,,"Z=",Z
End Sub
Sub Print3Str()
Print "X$=",X$,,"Y$=",Y$,,"Z$=",Z$
End Sub
}
Sort3
Maple
lst := sort([x,y,z]):
x,y,z := lst[1],lst[2],lst[3]:
- Example:
x := 'lions, tigers, and': y := 'bears, oh my!': z := '(from the "Wizard of OZ")':
>>>x; "(from the "Wizard of OZ")" >>>y; "bears, oh my!" >>>z; "lions, tigers, and"
x := 77444: y := -12: z := 0:
>>>x; -12 >>>y; 0 >>>z; 77444
Mathematica/Wolfram Language
All variables in Mathematica are typeless so the follow code works in all cases
{x, y, z} = Sort[{x, y, z}]
example:
x = 77444;
y = -12;
z = 0;
{x, y, z} = Sort[{x, y, z}];
{x, y, z}
- Output:
{-12, 0, 77444}
min
The sort3
operator updates the values of the variables given to it in the calling scope, much like passing by reference. A small drawback is that we must quote the symbols passed in, lest we lose access to them.
(=c =b =a (a -> b -> c ->) => '> sort -> c @ b @ a @) :sort3
"lions, tigers, and" :x
"bears, oh my!" :y
"(from the \"Wizard of OZ\")" :z
'x 'y 'z sort3
x puts!
y puts!
z puts!
77444 :x
-12 :y
0 :z
'x 'y 'z sort3
x puts!
y puts!
z puts!
- Output:
(from the "Wizard of OZ") bears, oh my! lions, tigers, and -12 0 77444
Modula-2
MODULE SortThreeVariables;
FROM FormatString IMPORT FormatString;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;
PROCEDURE SwapInt(VAR a,b : INTEGER);
VAR t : INTEGER;
BEGIN
t := a;
a := b;
b := t;
END SwapInt;
PROCEDURE Sort3Int(VAR x,y,z : INTEGER);
BEGIN
IF x<y THEN
IF z<x THEN
SwapInt(x,z);
END;
ELSIF y<z THEN
SwapInt(x,y);
ELSE
SwapInt(x,z);
END;
IF z<y THEN
SwapInt(y,z);
END;
END Sort3Int;
VAR
buf : ARRAY[0..63] OF CHAR;
a,b,c : INTEGER;
BEGIN
a := 77444;
b := -12;
c := 0;
FormatString("Before a=[%i]; b=[%i]; c=[%i]\n", buf, a, b, c);
WriteString(buf);
Sort3Int(a,b,c);
FormatString("Before a=[%i]; b=[%i]; c=[%i]\n", buf, a, b, c);
WriteString(buf);
ReadChar;
END SortThreeVariables.
Nanoquery
import sort
// sorting string literals
x = "lion, tigers, and"
y = "bears, oh my!"
z = "(from the \"Wizard of OZ\")"
varlist = sort({x,y,z})
x = varlist[0]
y = varlist[1]
z = varlist[2]
println x; println y; println z
// sorting integers
x = 77444
y = -12
z = 0
varlist = sort({x, y, z})
x = varlist[0]
y = varlist[1]
z = varlist[2]
println x; println y; println z
- Output:
(from the "Wizard of OZ") bears, oh my! lion, tigers, and -12 0 77444
Nim
proc sortThree[T](a, b, c: var T) =
# Bubble sort, why not?
while not (a <= b and b <= c):
if a > b: swap a, b
if b > c: swap b, c
proc testWith[T](a, b, c: T) =
var (x, y, z) = (a, b, c)
echo "Before: ", x, ", ", y, ", ", z
sortThree(x, y, z)
echo "After: ", x, ", ", y, ", ", z
testWith(6, 4, 2)
testWith(0.9, -37.1, 4.0)
testWith("lions", "tigers", "bears")
- Output:
Before: 6, 4, 2 After: 2, 4, 6 Before: 0.9, -37.1, 4.0 After: -37.1, 0.9, 4.0 Before: lions, tigers, bears After: bears, lions, tigers
OCaml
let sortrefs list =
let sorted = List.map ( ! ) list
|> List.sort (fun a b ->
if a < b then -1 else
if a > b then 1 else
0) in
List.iter2 (fun v x -> v := x) list sorted
open Printf
let test () =
let x = ref "lions, tigers, and" in
let y = ref "bears, oh my!" in
let z = ref "(from the \"Wizard of OZ\")" in
sortrefs [x; y; z];
print_endline "case 1:";
printf "\tx: %s\n" !x;
printf "\ty: %s\n" !y;
printf "\tz: %s\n" !z;
let x = ref 77444 in
let y = ref (-12) in
let z = ref 0 in
sortrefs [x; y; z];
print_endline "case 1:";
printf "\tx: %d\n" !x;
printf "\ty: %d\n" !y;
printf "\tz: %d\n" !z
- Output:
# test ();; case 1: x: (from the "Wizard of OZ") y: bears, oh my! z: lions, tigers, and case 1: x: -12 y: 0 z: 77444 - : unit = ()
Pascal
Pascal is a statically typed programming language. The data types of all variables and routine parameters need to be known in advance. The following program demonstrates sorting three strings, but can be easily adapted to work for integer and real variables as well.
program sortThreeVariables(output);
type
{ this Extended Pascal data type may hold up to 25 `char` values }
line = string(25);
{ this procedure sorts two lines }
procedure sortLines(var X, Y: line);
{ nested procedure allocates space for Z only if needed }
procedure swap;
var
Z: line;
begin
Z := X;
X := Y;
Y := Z
end;
begin
{ for lexical sorting write `if GT(X, Y) then` }
if X > Y then
begin
swap
end
end;
{ sorts three line variables’s values }
procedure sortThreeLines(var X, Y, Z: line);
begin
{ `var` parameters can be modified at the calling site }
sortLines(X, Y);
sortLines(X, Z);
sortLines(Y, Z)
end;
{ writes given lines on output preceded by `X = `, `Y = ` and `Z = ` }
procedure printThreeLines(protected X, Y, Z: line);
begin
{ `protected` parameters cannot be overwritten }
writeLn('X = ', X);
writeLn('Y = ', Y);
writeLn('Z = ', Z)
end;
{ === MAIN ============================================================= }
var
A, B: line;
{ for demonstration purposes: alternative method to initialize }
C: line value '(from the "Wizard of OZ")';
begin
A := 'lions, tigers, and';
B := 'bears, oh my!';
sortThreeLines(A, B, C);
printThreeLines(A, B, C)
end.
Perl
#!/usr/bin/env perl
use 5.010_000;
# Sort strings
my $x = 'lions, tigers, and';
my $y = 'bears, oh my!';
my $z = '(from the "Wizard of OZ")';
# When assigning a list to list, the values are mapped
( $x, $y, $z ) = sort ( $x, $y, $z );
say 'Case 1:';
say " x = $x";
say " y = $y";
say " z = $z";
# Sort numbers
$x = 77444;
$y = -12;
$z = 0;
# The sort function can take a customizing block parameter.
# The spaceship operator creates a by-value numeric sort
( $x, $y, $z ) = sort { $a <=> $b } ( $x, $y, $z );
say 'Case 2:';
say " x = $x";
say " y = $y";
say " z = $z";
- Output:
Case 1: x = (from the "Wizard of OZ") y = bears, oh my! z = lions, tigers, and Case 2: x = -12 y = 0 z = 77444
Phix
Phix is naturally polymorphic
with javascript_semantics object {x,y,z} = {"lions, tigers, and","bears, oh my","(from the \"Wizard of OZ\")"} ?{x,y,z} {x,y,z} = sort({x,y,z}) ?{x,y,z} {x,y,z} = {77444,-12,0} ?{x,y,z} {x,y,z} = sort({x,y,z}) ?{x,y,z}
- Output:
{"lions, tigers, and","bears, oh my","(from the \"Wizard of OZ\")"} {"(from the \"Wizard of OZ\")","bears, oh my","lions, tigers, and"} {77444,-12,0} {-12,0,77444}
PHP
<?php
//Sort strings
$x = 'lions, tigers, and';
$y = 'bears, oh my!';
$z = '(from the "Wizard of OZ")';
$items = [$x, $y, $z];
sort($items);
list($x, $y, $z) = $items;
echo <<<EOT
Case 1:
x = $x
y = $y
z = $z
EOT;
//Sort numbers
$x = 77444;
$y = -12;
$z = 0;
$items = [$x, $y, $z];
sort($items);
list($x, $y, $z) = $items;
echo <<<EOT
Case 2:
x = $x
y = $y
z = $z
EOT;
- Output:
Case 1: x = (from the "Wizard of OZ") y = bears, oh my! z = lions, tigers, and Case 2: x = -12 y = 0 z = 77444
PicoLisp
(let (X 77444 Y -12 Z 0)
(println X Y Z)
(mapc set '(X Y Z) (sort (list X Y Z)))
(println X Y Z) )
- Output:
77444 -12 0 -12 0 77444
Plain English
This will sort integers only.
To run:
Start up.
Sort three numbers.
Wait for the escape key.
Shut down.
To sort three numbers:
Put 77444 into an x number.
Put -12 into a y number.
Put 0 into a z number.
Write "===Before sorting===" on the console.
Write "x: " then the x on the console.
Write "y: " then the y on the console.
Write "z: " then the z on the console.
Sort the x and the y and the z.
Write "===After sorting===" on the console.
Write "x: " then the x on the console.
Write "y: " then the y on the console.
Write "z: " then the z on the console.
To sort a first number and a second number and a third number:
If the first number is greater than the second number, swap the first number with the second number.
If the second number is greater than the third number, swap the second number with the third number.
If the first number is greater than the second number, swap the first number with the second number.
- Output:
===Before sorting=== x: 77444 y: -12 z: 0 ===After sorting=== x: -12 y: 0 z: 77444
PureBasic
;sort three variables: x, y, z
;Macro handles any of the native types, including integers, floating point, and strings
;because the variable types are not declared but substituted during each instance of the macro.
;The sorting is in ascending order, i.e. x < y < z.
Macro sort3vars(x, y, z)
If x > y: Swap x, y: EndIf
If x > z: Swap x, z: EndIf
If y > z: Swap y, z: EndIf
EndMacro
;Macro to perform the sorting test for each variable type, again by substitution.
Macro test_sort(x, y, z)
PrintN("Variables before sorting: " + #CRLF$ + x + #CRLF$ + y + #CRLF$ + z + #CRLF$)
sort3vars(x, y, z)
PrintN("Variables after sorting: " + #CRLF$ + x + #CRLF$ + y + #CRLF$ + z + #CRLF$)
EndMacro
;Define three sets of variables each with a different type for testing
Define.s x, y, z ;string
x = "lions, tigers, and"
y = "bears, oh my!"
z = ~"(from the \"Wizard of OZ\")" ;uses an escaped string as one way to include quotation marks
Define x1 = 77444, y1 = -12, z1 = 0 ;integer
Define.f x2= 5.2, y2 = -1133.9, z2 = 0 ;floating point
If OpenConsole()
PrintN("Sort three variables" + #CRLF$)
test_sort(x, y, z) ;strings
test_sort(x1, y1, z1) ;integers
test_sort(x2, y2, z2) ;floating point
Print(#CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf
Sample output:
Sort three variables Variables before sorting: lions, tigers, and bears, oh my! (from the "Wizard of OZ") Variables after sorting: (from the "Wizard of OZ") bears, oh my! lions, tigers, and Variables before sorting: 77444 -12 0 Variables after sorting: -12 0 77444 Variables before sorting: 5.1999998093 -1133.9000244141 0 Variables after sorting: -1133.9000244141 0 5.1999998093
Python
Python2
This solution accepts 3 values either strings or numbers from user and then sort it in ascending order. This is implemented in Python 2.
#python2 Code for Sorting 3 values
a= raw_input("Enter values one by one ..\n1.").strip()
b=raw_input("2.").strip()
c=raw_input("3.").strip()
if a>b :
a,b = b,a
if a>c:
a,c = c,a
if b>c:
b,c = c,b
print(str(a)+" "+str(b)+" "+str(c))
Python3
The following uses Python3.6 f-strings and uses the built in sorted function and assignment to a target list.
while True:
x, y, z = eval(input('Three Python values: '))
print(f'As read: x = {x!r}; y = {y!r}; z = {z!r}')
x, y, z = sorted((x, y, z))
print(f' Sorted: x = {x!r}; y = {y!r}; z = {z!r}')
- Output:
Three Python values: 3, 2, 1 As read: x = 3; y = 2; z = 1 Sorted: x = 1; y = 2; z = 3 Three Python values: 'lions, tigers, and', 'bears, oh my!', '(from the "Wizard of OZ")' As read: x = 'lions, tigers, and'; y = 'bears, oh my!'; z = '(from the "Wizard of OZ")' Sorted: x = '(from the "Wizard of OZ")'; y = 'bears, oh my!'; z = 'lions, tigers, and' Three Python values: 77444, -12, 0 As read: x = 77444; y = -12; z = 0 Sorted: x = -12; y = 0; z = 77444 Three Python values:
Quackery
Quackery does not have variables, instead it has ancillary stacks, which, amongst their uses, can act as variables. Neither does it have operator overloading, so instead we will use sortwith >
to sort three integers into ascending numerical order, and sortwith $>
to sort three strings into ascending QACSFOT order.
(QACSFOT is the Quackery Arbitrary Character Sequence For Ordered Text, which is 0123456789AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz()[]{}<>~=+-*/^\|_.,:;?!'"`%@&#$
. Note that, unlike the even more arbitrary ASCII/Unicode character sequence, all the punctuation marks come after all the alphabetic characters, so the result of sorting the strings will vary from the result given in the task description.)
[ stack ] is x
[ stack ] is y
[ stack ] is z
$ 'lions, tigers, and' x put
$ 'bears, oh my!' y put
$ '(from the "Wizard of OZ")' z put
x take y take z take
3 pack sortwith $> unpack
z put y put x put
say " x = " x take echo$ cr
say " y = " y take echo$ cr
say " z = " z take echo$ cr
cr
77444 x put
-12 y put
0 z put
x take y take z take
3 pack sortwith > unpack
z put y put x put
say " x = " x take echo cr
say " y = " y take echo cr
say " z = " z take echo cr
- Output:
x = bears, oh my! y = lions, tigers, and z = (from the "Wizard of OZ") x = -12 y = 0 z = 77444
R
#lang R
assignVec <- Vectorize("assign", c("x", "value"))
`%<<-%` <- function(x, value) invisible(assignVec(x, value, envir = .GlobalEnv)) # define multiple global assignments operator
- Output:
x <- 'lions, tigers, and'
y <- 'bears, oh my!'
z <- '(from the "Wizard of OZ")'
c("x", "y", "z") %<<-% sort(c(x, y, z))
x
## [1] "(from the \"Wizard of OZ\")"
y
## [1] "bears, oh my!"
z
## [1] "lions, tigers, and"
x <- 77444
y <- -12
z <- 0
c("x", "y", "z") %<<-% sort(c(x, y, z))
x
## [1] -12
y
## [1] 0
z
## [1] 77444
Racket
Ugh... mutation. Anyway...
#lang racket
(define-syntax-rule (sort-3! x y z <?)
(begin
(define-syntax-rule (swap! x y) (let ((tmp x)) (set! x y) (set! y tmp)))
(define-syntax-rule (sort-2! x y) (when (<? y x) (swap! x y)))
(sort-2! x y)
(sort-2! x z)
(sort-2! y z)))
(module+ test
(require rackunit
data/order)
(define (test-permutations l <?)
(test-case
(format "test-permutations ~a" (object-name <?))
(for ((p (in-permutations l)))
(match-define (list a b c) p)
(sort-3! a b c <?)
(check-equal? (list a b c) l))))
(test-permutations '(1 2 3) <)
;; string sorting
(let ((x "lions, tigers, and")
(y "bears, oh my!")
(z "(from the \"Wizard of OZ\")"))
(sort-3! x y z string<?)
(for-each displayln (list x y z)))
(newline)
;; general data sorting
(define datum<? (order-<? datum-order))
(let ((x "lions, tigers, and")
(y "bears, oh my!")
(z '(from the "Wizard of OZ")))
(sort-3! x y z datum<?)
(for-each displayln (list x y z))))
- Output:
(from the "Wizard of OZ") bears, oh my! lions, tigers, and bears, oh my! lions, tigers, and (from the Wizard of OZ)
Raku
(formerly Perl 6)
Raku has a built in sort routine which uses a variation of quicksort. The built in sort routine will automatically select a numeric sort if given a list of Real numeric items and a lexical Unicode sort if given a list that contains strings. The default numeric sort won't sort complex numbers unless you give it a custom comparator. It is trivial to modify the sort comparator function to get whatever ordering you want though.
The list (77444, -12, 0) is a poor choice to demonstrate numeric sort since it will sort the same numerically or lexically. Instead we'll use (7.7444e4, -12, 18/2). ( A Num, an Int, and a Rat. )
# Sorting strings. Added a vertical bar between strings to make them discernable
my ($a, $b, $c) = 'lions, tigers, and', 'bears, oh my!', '(from "The Wizard of Oz")';
say "sorting: {($a, $b, $c).join('|')}";
say ($a, $b, $c).sort.join('|'), ' - standard lexical string sort';
# Sorting numeric things
my ($x, $y, $z) = 7.7444e4, -12, 18/2;
say "\nsorting: $x $y $z";
say ($x, $y, $z).sort, ' - standard numeric sort, low to high';
# Or, with a modified comparitor:
for -*, ' - numeric sort high to low',
~*, ' - lexical "string" sort',
*.chars, ' - sort by string length short to long',
-*.chars, ' - or long to short'
-> $comparitor, $type {
my ($x, $y, $z) = 7.7444e4, -12, 18/2;
say ($x, $y, $z).sort( &$comparitor ), $type;
}
say '';
# sort ALL THE THINGS
# sorts by lexical order with numeric values by magnitude.
.say for ($a, $b, $c, $x, $y, $z).sort;
- Output:
sorting: lions, tigers, and|bears, oh my!|(from "The Wizard of Oz") (from "The Wizard of Oz")|bears, oh my!|lions, tigers, and - standard lexical string sort sorting: 77444 -12 9 (-12 9 77444) - standard numeric sort, low to high (77444 9 -12) - numeric sort high to low (-12 77444 9) - lexical "string" sort (9 -12 77444) - sort by string length short to long (77444 -12 9) - or long to short (from "The Wizard of Oz") -12 9 77444 bears, oh my! lions, tigers, and
Red
Red can natively sort values of various types. For instance here (not exhaustive): strings, integers, floats, characters, IP addresses, email addresses, words (~ variable names).
foreach [x y z] [
"lions, tigers, and"
"bears, oh my!"
{(from the "Wizard of OZ")}
77444 -12 0
3.1416 3.1415926 3.141592654
#"z" #"0" #"A"
216.239.36.21 172.67.134.114 127.0.0.1
john@doe.org max@min.com cool@bi.net
potato carrot cabbage
][
set [x y z] sort reduce [x y z]
print ["x:" mold x "y:" mold y "z:" mold z]
]
- Output:
x: {(from the "Wizard of OZ")} y: "bears, oh my!" z: "lions, tigers, and" x: -12 y: 0 z: 77444 x: 3.1415926 y: 3.141592654 z: 3.1416 x: #"0" y: #"A" z: #"z" x: 127.0.0.1 y: 172.67.134.114 z: 216.239.36.21 x: cool@bi.net y: john@doe.org z: max@min.com x: cabbage y: carrot z: potato
REXX
Since Classic REXX has no native sorting built-in, here is an alternative algorithm.
generic
This version will sort numbers and/or literals.
The literals can be of any length (only limited by virtual memory or language limitations).
/*REXX program sorts three (any value) variables (X, Y, and Z) into ascending order.*/
parse arg x y z . /*obtain the three variables from C.L. */
if x=='' | x=="," then x= 'lions, tigers, and' /*Not specified? Use the default*/
if y=='' | y=="," then y= 'bears, oh my!' /* " " " " " */
if z=='' | z=="," then z= '(from "The Wizard of Oz")' /* " " " " " */
say '───── original value of X: ' x
say '───── original value of Y: ' y
say '───── original value of Z: ' z
if x>y then do; _= x; x= y; y= _; end /*swap the values of X and Y. */ /* ◄─── sorting.*/
if y>z then do; _= y; y= z; z= _; end /* " " " " Y " Z. */ /* ◄─── sorting.*/
if x>y then do; _= x; x= y; y= _; end /* " " " " X " Y. */ /* ◄─── sorting */
say /*stick a fork in it, we're all done. */
say '═════ sorted value of X: ' x
say '═════ sorted value of Y: ' y
say '═════ sorted value of Z: ' z
- output when using the default inputs:
───── original value of X: lions, tigers, and ───── original value of Y: bears, oh my! ───── original value of Z: (from "The Wizard of Oz") ═════ sorted value of X: (from "The Wizard of Oz") ═════ sorted value of Y: bears, oh my! ═════ sorted value of Z: lions, tigers, and
numeric only
This version will sort numbers (the numbers can be in any form, floating point and/or integer).
The maximum integer than be kept as an integer is (in this program) is 1,000 decimal digits.
/*REXX program sorts three (numeric) variables (X, Y, and Z) into ascending order. */
numeric digits 1000 /*handle some pretty gihugic integers. */ /*can be bigger.*/
parse arg x y z . /*obtain the three variables from C.L. */
if x=='' | x=="," then x= 77444 /*Not specified? Then use the default.*/
if y=='' | y=="," then y= -12 /* " " " " " " */
if z=='' | z=="," then z= 0 /* " " " " " " */
w= max( length(x), length(y), length(z) ) + 5 /*find max width of the values, plus 5.*/
say '───── original values of X, Y, and Z: ' right(x, w) right(y, w) right(z, w)
low = x /*assign a temporary variable. */
mid = y /* " " " " */
high= z /* " " " " */
x= min(low, mid, high) /*determine the lowest value of X,Y,Z. */ /* ◄─── sorting.*/
z= max(low, mid, high) /* " " highest " " " " " */ /* ◄─── sorting.*/
y= low + mid + high - x - z /* " " middle " " " " " */ /* ◄─── sorting.*/
/*stick a fork in it, we're all done. */
say '═════ sorted values of X, Y, and Z: ' right(x, w) right(y, w) right(z, w)
- output when using the default inputs:
───── original values of X, Y, and Z: 77444 -12 0 ═════ sorted values of X, Y, and Z: -12 0 77444
Ring
# Project : Sort three variables
x = 'lions, tigers, and'
y = 'bears, oh my!'
z = '(from the "Wizard of OZ")'
sortthree(x,y,z)
x = 77444
y = -12
z = 0
sortthree(x,y,z)
func sortthree(x,y,z)
str = []
add(str,x)
add(str,y)
add(str,z)
str = sort(str)
see "x = " + str[1] + nl
see "y = " + str[2] + nl
see "z = " + str[3] + nl
see nl
Output:
x = (from the "Wizard of OZ") y = bears, oh my! z = lions, tigers, and x = -12 y = 0 z = 77444
==Ring==
x = 77444
y = -12
z = 0
sList = sortList(x, y, z)
see sList + nl
x = 'lions, tigers, and'
y = 'bears, oh my!'
z = '(from the "Wizard of OZ")'
sList = sortList(x, y, z)
see sList + nl
func sortList (x, y, z)
aList = [x, y, z]
sList = sort(aList)
return sList
Output:
-12 0 77444 (from the "Wizard of OZ") bears, oh my! lions, tigers, and
RPL
≪ → x y z
≪ x y z 3 →LIST SORT LIST→ DROP
≫ ≫ 'SORT3' STO
"lions, tigers, and" "bears, oh my!" "(from the 'Wizard of OZ')" SORT3 77444 -12 9 SORT3
- Output:
6: "bears, oh my!" 5: "lions, tigers, and" 4: "(from the 'Wizard of OZ')" 3: -12 2: 9 1: 77444
Ruby
x = 'lions, tigers, and'
y = 'bears, oh my!'
z = '(from the "Wizard of OZ")'
x, y, z = [x, y, z].sort
puts x, y, z
x, y, z = 7.7444e4, -12, 18/2r # Float, Integer, Rational; taken from Raku
x, y, z = [x, y, z].sort
puts x, y, z
- Output:
(from the "Wizard of OZ") bears, oh my! lions, tigers, and -12 9/1 77444.0
Rust
fn main() {
let mut array = [5, 1, 3];
array.sort();
println!("Sorted: {:?}", array);
array.sort_by(|a, b| b.cmp(a));
println!("Reverse sorted: {:?}", array);
}
Scala
As a Functional Programming language embraces the use of immutable variables. Mutability (variables and states) is seen as evil. Scala works rather with transformed collection obtained by functions then mutable variable and variable state. So this task has no sense in modern programming.
Seed7
$ include "seed7_05.s7i";
const proc: genSort3 (in type: elemType) is func
begin
global
const proc: doSort3 (in var elemType: x, in var elemType: y, in var elemType: z) is func
local
var array elemType: sorted is 0 times elemType.value;
begin
writeln("BEFORE: x=[" <& x <& "]; y=[" <& y <& "]; z=[" <& z <& "]");
sorted := sort([](x, y, z));
x := sorted[1];
y := sorted[2];
z := sorted[3];
writeln("AFTER: x=[" <& x <& "]; y=[" <& y <& "]; z=[" <& z <& "]");
end func;
end global;
end func;
genSort3(integer);
genSort3(string);
const proc: main is func
begin
doSort3(77444, -12, 0);
doSort3("lions, tigers, and", "bears, oh my!", "(from the \"Wizard of OZ\")");
end func;
- Output:
BEFORE: x=[77444]; y=[-12]; z=[0] AFTER: x=[-12]; y=[0]; z=[77444] BEFORE: x=[lions, tigers, and]; y=[bears, oh my!]; z=[(from the "Wizard of OZ")] AFTER: x=[(from the "Wizard of OZ")]; y=[bears, oh my!]; z=[lions, tigers, and]
SenseTalk
Set x to "lions, tigers and"
Set y to "bears, oh my!"
Set z to "(from the Wizard of Oz)"
log x
log y
log z
set RosettaListAlpha to (x,y,z)
log RosettaListAlpha
sort RosettaListAlpha alphabetically
log RosettaListAlpha
LogSuccess "Alphabetical Sort Successful"
set (x,y,z) to RosettaListAlpha
log x
log y
log z
LogSuccess "Sorted Items back into Original Variables"
Set a to "77444"
set b to "-12"
set c to "0"
set d to "62224"
set RosettaListNum to (a,b,c,d)
log RosettaListNum
sort RosettaListNum numerically
log RosettaListNum
LogSuccess "Numerical Sort Successful"
set (a,b,c,d) to RosettaListNum
log a
log b
log c
log d
LogSuccess "Sorted Numbers back into Original Variables"
Sidef
Generalized solution, for an arbitrary number of variable references:
func sort_refs(*arr) {
arr.map{ *_ }.sort ~Z arr -> each { *_[1] = _[0] }
}
var x = 77444
var y = -12
var z = 0
sort_refs(\x, \y, \z)
say x
say y
say z
- Output:
-12 0 77444
Alternatively, without using a sorting function:
var x = 77444
var y = -12
var z = 0
(x, y) = (y, x) if (x > y)
(x, z) = (z, x) if (x > z)
(y, z) = (z, y) if (y > z)
say x
say y
say z
- Output:
-12 0 77444
Swift
func varSort<T: Comparable>(_ x: inout T, _ y: inout T, _ z: inout T) {
let res = [x, y, z].sorted()
x = res[0]
y = res[1]
z = res[2]
}
var x = "lions, tigers, and"
var y = "bears, oh my!"
var z = "(from the \"Wizard of OZ\")"
print("Before:")
print("x = \(x)")
print("y = \(y)")
print("z = \(z)")
print()
varSort(&x, &y, &z)
print("After:")
print("x = \(x)")
print("y = \(y)")
print("z = \(z)")
- Output:
Before: x = lions, tigers, and y = bears, oh my! z = (from the "Wizard of OZ") After: x = (from the "Wizard of OZ") y = bears, oh my! z = lions, tigers, and
Tcl
set x {lions, tigers, and}
set y {bears, oh my!}
set z {(from the "Wizard of OZ")}
lassign [lsort [list $x $y $z]] x y z
puts "x: $x"
puts "y: $y"
puts "z: $z"
set x 77444
set y -12
set z 0
lassign [lsort [list $x $y $z]] x y z
puts "x: $x"
puts "y: $y"
puts "z: $z"
- Output:
x: (from the "Wizard of OZ") y: bears, oh my! z: lions, tigers, and x: -12 y: 0 z: 77444
TXR
The following is a comprehensive solution to the general problem of sorting any number of mutable places. We develop a macro operator called sort-places
which is called with zero or more argument expressions that denote assignable places. The places are sorted in order according to the greater
function.
The zero and one argument cases are handled as no-ops; the arguments are not evaluated at all, even for their side effects if they have any. The two argument case is handled by generating a conditional which controls a single swap. The three-argument case performs up to three swaps.
For four or more arguments, a hidden vector object is generated. The values of the places are stuffed into the vector, which is then sorted, after which the values are retrieved and stored in the places.
All cases work in such a way that the place expressions are evaluated at most once, which is achieved by leveraging the simple-to-use placelet
macro.
(defmacro sort-places (. places)
(caseql (len places)
((0 1) nil)
(2 (with-gensyms (p0 p1)
^(placelet ((p0 (read-once ,[places 0]))
(p1 (read-once ,[places 1])))
(if (greater p0 p1)
(swap p0 p1)))))
(3 (with-gensyms (p0 p1 p2)
^(placelet ((p0 (read-once ,[places 0]))
(p1 (read-once ,[places 1]))
(p2 (read-once ,[places 2])))
(if (greater p0 p1)
(swap p0 p1))
(if (greater p1 p2)
(swap p1 p2))
(if (greater p0 p1)
(swap p0 p1)))))
(t (let ((gens [mapcar (ret (gensym)) places]))
(with-gensyms (vec)
^(placelet ,(zip gens places)
(let ((,vec (vec ,*gens)))
(nsort ,vec)
(set ,*(append-each ((g gens)
(i 0))
^(,g [,vec ,i]))))))))))
(prinl (sort-places))
(let ((x 1))
(sort-places x)
(prinl x))
(let ((x 2)
(y 1))
(sort-places x y)
(prinl (list x y)))
(let ((a 3)
(b 2)
(c 1))
(sort-places a b c)
(prinl (list a b c)))
(let ((a 4)
(b 3)
(c 2)
(d 1))
(sort-places a b c d)
(prinl (list a b c d)))
- Output:
nil 1 (1 2) (1 2 3) (1 2 3 4)
Visual Basic .NET
Module Module1
Sub Swap(Of T)(ByRef a As T, ByRef b As T)
Dim c = a
a = b
b = c
End Sub
Sub Sort(Of T As IComparable(Of T))(ByRef a As T, ByRef b As T, ByRef c As T)
If a.CompareTo(b) > 0 Then
Swap(a, b)
End If
If a.CompareTo(c) > 0 Then
Swap(a, c)
End If
If b.CompareTo(c) > 0 Then
Swap(b, c)
End If
End Sub
Sub Main()
Dim x = 77444
Dim y = -12
Dim z = 0
Sort(x, y, z)
Console.WriteLine((x, y, z))
Dim a = "lions, tigers, and"
Dim b = "bears, oh my!"
Dim c = "(from the 'Wizard of OZ')"
Sort(a, b, c)
Console.WriteLine((a, b, c))
End Sub
End Module
- Output:
(-12, 0, 77444) ((from the 'Wizard of OZ'), bears, oh my!, lions, tigers, and)
Wren
import "./sort" for Sort
import "./fmt" for Fmt
var sort3 = Fn.new { |x, y, z|
var a = [x, y, z]
Sort.insertion(a)
x = a[0]
y = a[1]
z = a[2]
Fmt.print(" x = $s\n y = $s\n z = $s", x, y, z)
}
System.print("After sorting strings:")
var x = "lions, tigers, and"
var y = "bears, oh my!"
var z = "(from the \"Wizard of OZ\")"
sort3.call(x, y, z)
System.print("\nAfter sorting integers:")
x = 77444
y = -12
z = 0
sort3.call(x, y, z)
System.print("\nAfter sorting floats:")
x = 11.3
y = -9.7
z = 11.17
sort3.call(x, y, z)
- Output:
After sorting strings: x = (from the "Wizard of OZ") y = bears, oh my! z = lions, tigers, and After sorting integers: x = -12 y = 0 z = 77444 After sorting floats: x = -9.7 y = 11.17 z = 11.3
zkl
This solution uses list assignment and list sorting. Lists are not homogeneous, but sorting usually expects that. If that is a problem, you can give the sort a compare function. Numbers (real and integer) are homogeneous enough to sort.
x,y,z := "lions, tigers, and", "bears, oh my!", 0'|(from the "Wizard of OZ")|;
x,y,z = List(x,y,z).sort();
println(x," | ",y," | ",z);
x,y,z := 77444, -12, 0;
x,y,z = List(x,y,z).sort();
println(x," ",y," ",z);
- Output:
(from the "Wizard of OZ") | bears, oh my! | lions, tigers, and -12 0 77444
- Programming Tasks
- Sorting Algorithms
- Sorting
- 11l
- 8086 Assembly
- Ada
- Aime
- ALGOL 68
- Amazing Hopper
- APL
- AppleScript
- Arturo
- AutoHotkey
- BCPL
- C
- C sharp
- C++
- CLU
- COBOL
- Cowgol
- D
- EasyLang
- EDSAC order code
- Elena
- Elixir
- F Sharp
- Factor
- FALSE
- FreeBASIC
- Forth
- Integers
- Strings
- Fortran
- Fōrmulæ
- Free Pascal
- Frink
- Go
- Haskell
- IS-BASIC
- J
- Java
- JavaScript
- Jq
- Jsish
- Julia
- Kotlin
- Ksh
- Little Man Computer
- Lua
- M2000 Interpreter
- Maple
- Mathematica
- Wolfram Language
- Min
- Modula-2
- Examples needing attention
- Nanoquery
- Nim
- OCaml
- Pascal
- Perl
- Phix
- PHP
- PicoLisp
- Plain English
- PureBasic
- Python
- Quackery
- R
- Racket
- Raku
- Red
- REXX
- Ring
- RPL
- Ruby
- Rust
- Seed7
- SenseTalk
- Sidef
- Swift
- Tcl
- TXR
- Visual Basic .NET
- Wren
- Wren-sort
- Wren-fmt
- Zkl