Sort three variables: Difference between revisions

(→‎{{header|AppleScript}}: Added alternative code.)
 
(46 intermediate revisions by 32 users not shown)
Line 2:
[[Category:Sorting]]
{{Sorting Algorithm}}
 
;Task:
;Task:
Sort   (the values of)   three variables   ('''X''',   '''Y''',   and   '''Z''')   that contain any value   (numbers and/or literals).
 
Line 39 ⟶ 40:
 
One algorithm could be:
Θ<big><big>&bull;</big></big> store the three variables &nbsp; '''x''', '''y''', and '''z'''
into an array (or a list) &nbsp; '''A'''
&nbsp;
 
Θ<big><big>&bull;</big></big> sort (the three elements of) the array &nbsp; '''A'''
&nbsp;
 
Θ<big><big>&bull;</big></big> extract the three elements from the array and place them in the
variables '''x''', '''y''', and '''z''' &nbsp; in order of extraction
 
Line 63 ⟶ 64:
Show the results of the sort here on this page using at least the values of those shown above.
<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}}==
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO;
with Ada.Strings.Unbounded;
 
Line 128 ⟶ 186:
Test_Unbounded_Sort;
Test_Integer_Sort;
end Sort_Three;</langsyntaxhighlight>
 
{{out}}
Line 140 ⟶ 198:
 
=={{header|Aime}}==
<langsyntaxhighlight lang="aime">integer a, b, c;
index i;
text x, y, z;
Line 167 ⟶ 225:
c = i.if_pick;
 
o_form("~\n~\n~\n", a, b, c);</langsyntaxhighlight>
{{out}}
<pre>(from the "Wizard of OZ")
Line 183 ⟶ 241:
<br>
As the task only requires sorting three values, we use a simple, three-element specific sort routine.
<langsyntaxhighlight lang="algol68">BEGIN
# MODE that can hold integers and strings - would need to be extended to #
# allow for other types #
Line 232 ⟶ 290:
sort 3( x, y, z );
print( ( x, newline, y, newline, z, newline ) )
END</langsyntaxhighlight>
{{out}}
<pre>(from the "Wizard of OZ")
Line 240 ⟶ 298:
+0
+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>
 
=={{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}}==
 
<langsyntaxhighlight lang="applescript">set x to "lions, tigers, and"
set y to "bears, oh my!"
set z to "(from the \"Wizard of OZ\")"
Line 253 ⟶ 401:
end if
 
return {x, y, z}</langsyntaxhighlight>
 
{{output}}
<pre>{"(from the \"Wizard of OZ\")", "bears, oh my!", "lions, tigers, and"}</pre>
 
<langsyntaxhighlight lang="applescript">set x to 77444
set y to -12
set z to 0
Line 268 ⟶ 416:
end if
 
return {x, y, z}</langsyntaxhighlight>
 
{{output}}
Line 275 ⟶ 423:
Longer, but more efficiently:
 
<langsyntaxhighlight lang="applescript">set x to "lions, tigers, and"
set y to "bears, oh my!"
set z to "(from the \"Wizard of OZ\")"
Line 297 ⟶ 445:
end tell
 
return {x, y, z}</langsyntaxhighlight>
 
=={{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}}==
<langsyntaxhighlight AutoHotkeylang="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
}</langsyntaxhighlight>
Examples:<langsyntaxhighlight AutoHotkeylang="autohotkey">x = lions, tigers, and
y = bears, oh my!
z = (from the "Wizard of OZ")
Line 318 ⟶ 486:
SortThreeVariables(x,y,z)
MsgBox % x "`n" y "`n" z
return</langsyntaxhighlight>
Outputs:<pre>---------------------------
(from the "Wizard of OZ")
Line 328 ⟶ 496:
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}}==
Line 335 ⟶ 581:
 
===Generic Implementation===
<syntaxhighlight lang="c">
<lang C>
#include<string.h>
#include<stdlib.h>
Line 344 ⟶ 590:
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;
}
</langsyntaxhighlight>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
Line 409 ⟶ 655:
</pre>
===Task Specific Implementation===
<syntaxhighlight lang="c">
<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>
</lang>
Output :
<pre>Before sorting :
Line 450 ⟶ 696:
=={{header|C sharp}}==
{{works with|C sharp|7.0}}
<langsyntaxhighlight lang="csharp">using System;
public class Program
{
Line 480 ⟶ 726:
if (b.CompareTo(c) > 0) (b, c) = (c, b);
}
}</langsyntaxhighlight>
{{out}}
<pre>(-12, 0, 77444)
Line 486 ⟶ 732:
 
=={{header|C++}}==
<langsyntaxhighlight Cpplang="cpp">#include <iostreamalgorithm>
#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.push_backbegin( x );, v.push_backend( y ); v.push_back( z );
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];
}
int main(int argc, char* argv[]) {
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";
Line 519 ⟶ 754:
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";
 
return 0;
}
</syntaxhighlight>
</lang>
{{out}}
<pre>-12
0
77444
 
(from the "Wizard of OZ")
bears, oh my!
lions, tigers, and
 
-9.7
11.17
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}}==
<langsyntaxhighlight COBOLlang="cobol"> program-id. 3var.
data division.
working-storage section.
Line 581 ⟶ 876:
stop run
.
end program 3var.</langsyntaxhighlight>
{{out}}
<pre>x = (from the "Wizard of OZ")
Line 590 ⟶ 885:
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}}==
<langsyntaxhighlight Dlang="d">import std.stdio;
 
void main() {
Line 626 ⟶ 978:
swap(y,z);
}
}</langsyntaxhighlight>
 
{{out}}
Line 633 ⟶ 985:
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 56.0x :
<langsyntaxhighlight lang="elena">import extensions;
sortThree(ref object a, ref object b, ref object c)
Line 660 ⟶ 1,103:
console.printLine(x,",",y,",",z);
console.printLine(a,",",b,",",c)
}</langsyntaxhighlight>
{{out}}
<pre>
Line 668 ⟶ 1,111:
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">x = 'lions, tigers, and'
y = 'bears, oh my!'
z = '(from the "Wizard of OZ")'
Line 680 ⟶ 1,123:
 
[x, y, z] = Enum.sort([x, y, z])
IO.puts "x = #{x}\ny = #{y}\nz = #{z}"</langsyntaxhighlight>
{{out}}
<pre>x = (from the "Wizard of OZ")
Line 691 ⟶ 1,134:
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight 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>
</lang>
{{out}}
<pre>(from the "Wizard of OZ")
Line 702 ⟶ 1,145:
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">USING: arrays io kernel prettyprint sequences sorting ;
IN: rosetta-code.sort-three
 
Line 712 ⟶ 1,155:
sort3 [ print ] tri@
 
77444 -12 0 sort3 [ . ] tri@</langsyntaxhighlight>
{{out}}
<pre>(from the "Wizard of OZ")
Line 720 ⟶ 1,163:
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}}==
Line 730 ⟶ 1,259:
typically be used directly from the stack by a subsequent operation in the
program.
<LANGsyntaxhighlight lang="forth" lines>\ sort 3 integers
VARIABLE X VARIABLE Y VARIABLE Z
 
Line 739 ⟶ 1,268:
2DUP < IF SWAP THEN ;
 
: SORT3INTS ( a b c -- c b a) ?SWAP >R ?SWAP R> ?SWAP ;</LANGsyntaxhighlight>
 
Testing is done using the Forth console using '?' to view VARIABLE contents
Line 754 ⟶ 1,283:
==={{header|Strings}}===
Strings require extending the language but the primitives needed are part of ANS/ISO Forth.
<LANGsyntaxhighlight lang="forth" lines>DECIMAL
: BUFFER: ( n -- ) CREATE ALLOT ;
 
Line 779 ⟶ 1,308:
\ 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 ; </LANGsyntaxhighlight>
With these extensions we can do the same testing at the Forth console and
examine the string order with '.STRS'.
Line 807 ⟶ 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.
 
One could make rather more use of the facilities of F90 and define a compound data type, such as <langsyntaxhighlight Fortranlang="fortran"> TYPE(MONGREL)
INTEGER TYPEIS
INTEGER VI
Line 814 ⟶ 1,343:
...etc...
END TYPE MONGREL
TYPE (MONGREL) DOG </langsyntaxhighlight>
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. <langsyntaxhighlight Fortranlang="fortran"> 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.
</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.
<pre> Supplied: >lions, tigers, and < >bears, oh my! < >(from the "Wizard of OZ") <
Line 855 ⟶ 1,384:
Supplied: >77444 < > -12 < > 0 <
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>
 
=={{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.
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,032 ⟶ 1,672:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>sorted strings:
Line 1,052 ⟶ 1,692:
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.
 
<langsyntaxhighlight Haskelllang="haskell">import Data.List (sort)
 
sortedTriple
Line 1,076 ⟶ 1,716:
("lions, tigers, and", "bears, oh my!", "(from the \"Wizard of OZ\")")
print $ sortedTriple (77444, -12, 0)
print $ sortedListfromTriple (77444, -12, 0)</langsyntaxhighlight>
{{Out}}
<pre>("(from the \"Wizard of OZ\")","bears, oh my!","lions, tigers, and")
Line 1,084 ⟶ 1,724:
 
=={{header|IS-BASIC}}==
<langsyntaxhighlight ISlang="is-BASICbasic">100 LET X=77444:LET Y=-12:LET Z=0
110 PRINT X;Y;Z
120 CALL SHORT(X,Y,Z)
Line 1,092 ⟶ 1,732:
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</langsyntaxhighlight>
{{out}}
<pre> 77444 -12 0
Line 1,099 ⟶ 1,739:
=={{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:
<langsyntaxhighlight Jlang="j"> x =: 'lions, tigers, and'
y =: 'bears, oh my!'
z =: '(from the "Wizard of OZ")'
Line 1,119 ⟶ 1,759:
0
z
77444</langsyntaxhighlight>
 
=={{header|Java}}==
<syntaxhighlight lang="java">
<lang Java>
import java.util.Comparator;
import java.util.stream.Stream;
Line 1,165 ⟶ 1,805:
}
}
</syntaxhighlight>
</lang>
{{out}}
<pre>Sorted values: 11 21 82
Line 1,172 ⟶ 1,812:
 
=={{header|JavaScript}}==
<langsyntaxhighlight JavaScriptlang="javascript">const printThree = (note, [a, b, c], [a1, b1, c1]) => {
console.log(`${note}
${a} is: ${a1}
Line 1,198 ⟶ 1,838:
};
sortThree();
</syntaxhighlight>
</lang>
{{out}}
<pre>Before Sorting
Line 1,227 ⟶ 1,867:
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.
 
<langsyntaxhighlight lang="jq">def example1:
{x: "lions, tigers, and",
y: "bears, oh my",
Line 1,237 ⟶ 1,877:
y: -12,
z: 0
};</langsyntaxhighlight>
 
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]) ) ;</langsyntaxhighlight>
 
Examples:
<syntaxhighlight lang ="jq">example1 | sortVariables</langsyntaxhighlight>
{{out}}
<pre>{
Line 1,254 ⟶ 1,894:
}
</pre>
<syntaxhighlight lang ="jq">example2 | sortVariables</langsyntaxhighlight>
{{out}}<pre>
{
Line 1,263 ⟶ 1,903:
 
=={{header|Jsish}}==
<langsyntaxhighlight lang="javascript">#!/usr/bin/env jsish
/* Sort three variables, in Jsish. semi-colon start/end for unit test echo */
 
Line 1,350 ⟶ 1,990:
z ==> 1 string
=!EXPECTEND!=
*/</langsyntaxhighlight>
 
{{out}}
Line 1,383 ⟶ 2,023:
 
=={{header|Julia}}==
<langsyntaxhighlight lang="julia"># v0.6
 
a, b, c = "lions, tigers, and", "bears, oh my!", "(from the \"Wizard of OZ\")"
Line 1,391 ⟶ 2,031:
a, b, c = 77444, -12, 0
a, b, c = sort([a, b, c])
@show a b c</langsyntaxhighlight>
 
{{out}}
Line 1,403 ⟶ 2,043:
=={{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:
<langsyntaxhighlight lang="scala">// version 1.1.2
 
inline fun <reified T : Comparable<T>> sortThree(x: T, y: T, z: T): Triple<T, T, T> {
Line 1,440 ⟶ 2,080:
z3 = t3.third
printThree(x3, y3, z3)
}</langsyntaxhighlight>
 
{{out}}
Line 1,454 ⟶ 2,094:
y = 41.7
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>
 
 
=={{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.
<langsyntaxhighlight Lualang="lua">function variadicSort (...)
local t = {}
for _, x in pairs{...} do
Line 1,482 ⟶ 2,326:
print("\ty = " .. y)
print("\tz = " .. z)
end</langsyntaxhighlight>
{{out}}
<pre>Case 1
Line 1,504 ⟶ 2,348:
Modules and Functions have a special list, where included at definition time, end excluded when parent exit.
 
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module Sort3 {
Let X=77744, Y=-12, Z=0
Line 1,536 ⟶ 2,380:
}
Sort3
</syntaxhighlight>
</lang>
 
=={{header|Maple}}==
<langsyntaxhighlight Maplelang="maple">lst := sort([x,y,z]):
x,y,z := lst[1],lst[2],lst[3]:</langsyntaxhighlight>
{{Out|Example}}
x := 'lions, tigers, and':
Line 1,561 ⟶ 2,405:
77444</pre>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
{{Output?}}
All variables in Mathematica are typeless so the follow code works in all cases
<langsyntaxhighlight Mathematicalang="mathematica">{x, y, z} = Sort[{x, y, z}]</langsyntaxhighlight>
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.
<langsyntaxhighlight lang="min">(=c =b =a (a -> b -> c ->) => '> sort -> c @ b @ a @) :sort3
 
"lions, tigers, and" :x
Line 1,587 ⟶ 2,438:
x puts!
y puts!
z puts!</langsyntaxhighlight>
{{out}}
<pre>
Line 1,600 ⟶ 2,451:
=={{header|Modula-2}}==
{{Output?}}
<langsyntaxhighlight lang="modula2">MODULE SortThreeVariables;
FROM FormatString IMPORT FormatString;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;
Line 1,643 ⟶ 2,494:
 
ReadChar;
END SortThreeVariables.</langsyntaxhighlight>
 
=={{header|Nanoquery}}==
<langsyntaxhighlight lang="nanoquery">import sort
 
// sorting string literals
Line 1,670 ⟶ 2,521:
y = varlist[1]
z = varlist[2]
println x; println y; println z</langsyntaxhighlight>
{{out}}
<pre>(from the "Wizard of OZ")
Line 1,678 ⟶ 2,529:
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}}==
<langsyntaxhighlight lang="ocaml">let sortrefs list =
let sorted = List.map ( ! ) list
|> List.sort (fun a b ->
Line 1,707 ⟶ 2,583:
printf "\tx: %d\n" !x;
printf "\ty: %d\n" !y;
printf "\tz: %d\n" !z</langsyntaxhighlight>
 
{{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}}==
Line 1,725 ⟶ 2,662:
{{works with|Perl|5.10+}}
 
<langsyntaxhighlight Perllang="perl">#!/usr/bin/env perl
use 5.010_000;
 
Line 1,755 ⟶ 2,692:
say " x = $x";
say " y = $y";
say " z = $z";</langsyntaxhighlight>
 
{{out}}
Line 1,770 ⟶ 2,707:
=={{header|Phix}}==
Phix is naturally polymorphic
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>object {x,y,z} = {"lions, tigers, and","bears, oh my","(from the \"Wizard of OZ\")"}
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
?{x,y,z}
<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>
{x,y,z} = sort({x,y,z})
<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>
?{x,y,z}
<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>
 
{x,y,z} = {77444,-12,0}
<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>
?{x,y,z}
<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>
{x,y,z} = sort({x,y,z})
<!--</syntaxhighlight>-->
?{x,y,z}</lang>
{{out}}
<pre>{"lions, tigers, and","bears, oh my","(from the \"Wizard of OZ\")"}
Line 1,786 ⟶ 2,723:
 
=={{header|PHP}}==
<langsyntaxhighlight lang="php"><?php
//Sort strings
$x = 'lions, tigers, and';
Line 1,821 ⟶ 2,758:
EOT;
 
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,835 ⟶ 2,772:
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="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) )</langsyntaxhighlight>
{{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}}==
<langsyntaxhighlight lang="purebasic">;sort three variables: x, y, z
 
;Macro handles any of the native types, including integers, floating point, and strings
Line 1,883 ⟶ 2,858:
Print(#CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf</langsyntaxhighlight>
Sample output:
<pre>Sort three variables
Line 1,922 ⟶ 2,897:
===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.
<langsyntaxhighlight lang="python">
#python2 Code for Sorting 3 values
a= raw_input("Enter values one by one ..\n1.").strip()
Line 1,934 ⟶ 2,909:
b,c = c,b
print(str(a)+" "+str(b)+" "+str(c))
</syntaxhighlight>
</lang>
 
===Python3===
The following uses Python3.6 f-strings and uses the built in sorted function and assignment to a target list.
<langsyntaxhighlight 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}')</langsyntaxhighlight>
 
{{out}}
Line 1,958 ⟶ 2,933:
 
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>
</lang>
 
{{out}}
 
<syntaxhighlight lang="text">
x <- 'lions, tigers, and'
y <- 'bears, oh my!'
Line 1,997 ⟶ 3,020:
z
## [1] 77444
</syntaxhighlight>
</lang>
 
=={{header|Racket}}==
Line 2,003 ⟶ 3,026:
Ugh... mutation. Anyway...
 
<syntaxhighlight lang="text">#lang racket
 
(define-syntax-rule (sort-3! x y z <?)
Line 2,042 ⟶ 3,065:
(z '(from the "Wizard of OZ")))
(sort-3! x y z datum<?)
(for-each displayln (list x y z))))</langsyntaxhighlight>
 
{{out}}
Line 2,060 ⟶ 3,083:
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. )
 
<syntaxhighlight lang="raku" perl6line># 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('|')}";
Line 2,083 ⟶ 3,106:
# sort ALL THE THINGS
# sorts by lexical order with numeric values by magnitude.
.say for ($a, $b, $c, $x, $y, $z).sort;</langsyntaxhighlight>
 
{{out}}
Line 2,102 ⟶ 3,125:
bears, oh my!
lions, tigers, and</pre>
 
=={{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).
<syntaxhighlight lang="red">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]
]</syntaxhighlight>
{{out}}
<pre>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</pre>
 
=={{header|REXX}}==
Line 2,109 ⟶ 3,157:
 
The literals can be of any length &nbsp; (only limited by virtual memory or language limitations).
<langsyntaxhighlight 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. */
if x=='' | x=="," then x= 'lions, tigers, and' /*Not specified? Use the default*/
Line 2,123 ⟶ 3,171:
say '═════ sorted value of X: ' x
say '═════ sorted value of Y: ' y
say '═════ sorted value of Z: ' z</langsyntaxhighlight>
{{out|output|text=when using the default inputs:}}
<pre>
Line 2,139 ⟶ 3,187:
 
The maximum integer than be kept &nbsp; ''as an integer'' &nbsp; is &nbsp; (in this program) &nbsp; is 1,000 decimal digits.
<langsyntaxhighlight 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.*/
parse arg x y z . /*obtain the three variables from C.L. */
Line 2,154 ⟶ 3,202:
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)</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default inputs:}}
<pre>
Line 2,162 ⟶ 3,210:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring"># Project : Sort three variables
 
x = 'lions, tigers, and'
Line 2,183 ⟶ 3,231:
see "z = " + str[3] + nl
see nl
</syntaxhighlight>
</lang>
Output:
<pre>x = (from the "Wizard of OZ")
Line 2,192 ⟶ 3,240:
y = 0
z = 77444</pre> =={{header|Ring}}==
<langsyntaxhighlight lang="ring">x = 77444
y = -12
z = 0
Line 2,208 ⟶ 3,256:
sList = sort(aList)
return sList
</syntaxhighlight>
</lang>
Output:
<pre>-12
Line 2,218 ⟶ 3,266:
lions, tigers, and</pre>
 
==Scala{{header|RPL}}==
{{works with|HP|48}}
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.
≪ → 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}}==
<langsyntaxhighlight lang="ruby">x = 'lions, tigers, and'
y = 'bears, oh my!'
z = '(from the "Wizard of OZ")'
Line 2,228 ⟶ 3,291:
puts x, y, z
 
x, y, z = 7.7444e4, -12, 18/2r # Float, Integer, Rational; taken from Perl 6Raku
x, y, z = [x, y, z].sort
puts x, y, z
</syntaxhighlight>
</lang>
{{Out}}
<pre>(from the "Wizard of OZ")
Line 2,239 ⟶ 3,302:
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}}==
 
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const proc: genSort3 (in type: elemType) is func
Line 2,270 ⟶ 3,346:
doSort3(77444, -12, 0);
doSort3("lions, tigers, and", "bears, oh my!", "(from the \"Wizard of OZ\")");
end func;</langsyntaxhighlight>
 
{{out}}
Line 2,282 ⟶ 3,358:
=={{header|SenseTalk}}==
 
<langsyntaxhighlight lang="sensetalk">Set x to "lions, tigers and"
Set y to "bears, oh my!"
Set z to "(from the Wizard of Oz)"
Line 2,321 ⟶ 3,397:
log d
 
LogSuccess "Sorted Numbers back into Original Variables"</langsyntaxhighlight>
 
=={{header|Sidef}}==
Generalized solution, for an arbitrary number of variable references:
<langsyntaxhighlight lang="ruby">func sort_refs(*arr) {
arr.map{ *_ }.sort ~Z arr -> each { *_[1] = _[0] }
}
Line 2,337 ⟶ 3,413:
say x
say y
say z</langsyntaxhighlight>
{{out}}
<pre>-12
Line 2,343 ⟶ 3,419:
77444</pre>
Alternatively, without using a sorting function:
<langsyntaxhighlight lang="ruby">var x = 77444
var y = -12
var z = 0
Line 2,353 ⟶ 3,429:
say x
say y
say z</langsyntaxhighlight>
{{out}}
<pre>-12
Line 2,361 ⟶ 3,437:
=={{header|Swift}}==
 
<langsyntaxhighlight lang="swift">func varSort<T: Comparable>(_ x: inout T, _ y: inout T, _ z: inout T) {
let res = [x, y, z].sorted()
 
Line 2,384 ⟶ 3,460:
print("x = \(x)")
print("y = \(y)")
print("z = \(z)")</langsyntaxhighlight>
 
{{out}}
Line 2,399 ⟶ 3,475:
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">
set x {lions, tigers, and}
set y {bears, oh my!}
Line 2,420 ⟶ 3,496:
puts "y: $y"
puts "z: $z"
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,430 ⟶ 3,506:
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#}}
<langsyntaxhighlight lang="vbnet">Module Module1
 
Sub Swap(Of T)(ByRef a As T, ByRef b As T)
Line 2,467 ⟶ 3,612:
End Sub
 
End Module</langsyntaxhighlight>
{{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>
 
=={{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.
<langsyntaxhighlight 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();
println(x," | ",y," | ",z);
Line 2,480 ⟶ 3,676:
x,y,z := 77444, -12, 0;
x,y,z = List(x,y,z).sort();
println(x," ",y," ",z);</langsyntaxhighlight>
{{out}}
<pre>(from the "Wizard of OZ") | bears, oh my! | lions, tigers, and
490

edits