Sort the values of three variables X, Y, and Z (containing
numbers and/or strings). If sorting mixed types is not possible,
just sort numbers and note the supported numeric type.
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.
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
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
---------------------------
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#
Works with C sharp|7.0
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 <iostream>
#include <string>
#include <vector>
template < class T >
void sort3( T& x, T& y, T& z) {
std::vector<T> v;
v.push_back( x ); v.push_back( 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";
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";
return 0;
}
Output:
-12
0
77444
(from the "Wizard of OZ")
bears, oh my!
lions, tigers, and
-9.7
11.17
11.3
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
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]
Elena
ELENA 4.1 :
import system'routines;
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
=={{header|F_Sharp|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
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.
: 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
```txt
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>
=
## Strings
=
Strings require extending the language but the primitives needed are part of ANS/ISO Forth.
<LANG>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 ```Fortran 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. ```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. ``` 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. ```txt 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 < ``` ## 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. ```go 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: ```txt 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. ```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) ``` Output: ```txt ("(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 ```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: ```txt 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: ```J x =: 'lions, tigers, and' y =: 'bears, oh my!' z =: '(from the "Wizard of OZ")' 'x y z'=: /:~".'x;y;
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.
```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!
```
Output:
```txt
(from the "Wizard of OZ")
bears, oh my!
lions, tigers, and
-12
0
77444
```
## Modula-2
```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