The procedure order
accepts three integer parameters. After a call to
order
, the values in the parameters are such that
order
; that is, after the call each parameter has a value held by a
parameter before the call.
For example, if the values of the parameters to order
before the call
are 2, 3, and 1 in left to right order, than after the call to order
, the
values in the parameters will be 1, 2, and 3.
order
.
With pointers it's
void order(int * ip, int * jp, int * kp);
void order(int & i, int & j, int k);
order
.
A pointer-based implementation
static void swap_if_greater(int * ip, int * jp) { // Permute the values *ip and *jp so that *ip <= *jp. if (*ip > *jp) { int t = *ip; *ip = *jp; *jp = t; } } void order(int * ip, int * jp, int * kp) { // Permute the values *ip, *jp, and *kp so that *ip <= *jp <= *kp. swap_if_greater(ip, jp); // *ip <= *jp. swap_if_greater(ip, kp); // *ip <= *jp and *ip <= *kp. swap_if_greater(jp, kp); // *ip <= *jp and *ip < *kp and *jp <= *kp. }
static void swap_if_greater(int & i, int & j) { // Permute the values i and j so that i <= j. if (i > j) { int t = i; i = j; j = t; } } void order(int & i, int & j, int & k) { // Permute the values i, j, and k so that i <= j <= k. swap_if_greater(i, j); // i <= j. swap_if_greater(i, k); // i <= j and i <= k. swap_if_greater(j, k); // i <= j and i < k and j <= k. }
order
call) that you might use to check the behavior of your
order
implementation.
A pointer-based test:
int i = 2; int j = 3; int k = 1; order(&i, &j, &k); if ((i != 1) || (j != 2) || (k != 3)) cerr << "values out of order.\n";
int i = 2; int j = 3; int k = 1; order(i, j, k); if ((i != 1) || (j != 2) || (k != 3)) cerr << "values out of order.\n";
This page last modified on 8 August 2001.