Sort three variables: Difference between revisions
Content added Content deleted
m (→{{header|Nim}}) |
Not a robot (talk | contribs) (Add BCPL) |
||
Line 370: | Line 370: | ||
77444 |
77444 |
||
---------------------------</pre> |
---------------------------</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. |
|||
<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') |
|||
$)</lang> |
|||
{{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}}== |
=={{header|C}}== |