# include void sort_3ints ( int a, int b, int c ); void sort_vec ( int d[3] ); void sort_3int_pointers ( int *a, int *b, int *c ); int main ( ) { int a; int b; int c; int d[3]; // // Call a function to sort 3 integers. // Why are they unsorted when the call is done? // a = 2; b = 1; c = 3; printf ( "Before call to SORT_3INTS, A = %i, B = %i, C = %i\n", a, b, c ); sort_3ints ( a, b, c ); printf ( "After call to SORT_3INTS, A = %i, B = %i, C = %i\n", a, b, c ); // // Call a function to sort 3 integers stored in an array. // They are sorted when the call is done. // d[0] = 2; d[1] = 1; d[2] = 3; printf ( "\n" ); printf ( "Before call to SORT_VEC, D[0] = %i, D[1] = %i, D[2] = %i\n", d[0], d[1], d[2] ); sort_vec ( d ); printf ( "After call to SORT_VEC, D[0] = %i, D[1] = %i, D[2] = %i\n", d[0], d[1], d[2] ); // // Call a function to sort 3 integers, using pointers. // This time, the values are sorted when the function is over. // // The explanation is that scalar input arguments are copied before being sent // to a function, and changes to the copies don't affect the original. // If we want to change the originals, we have to pass them as pointers. // a = 2; b = 1; c = 3; printf ( "\n" ); printf ( "Before call to SORT_3INT_POINTERS, A = %i, B = %i, C = %i\n", a, b, c ); sort_3int_pointers ( &a, &b, &c ); printf ( "After call to SORT_3INT_POINTERS, A = %i, B = %i, C = %i\n", a, b, c ); return 0; } void sort_3ints ( int a, int b, int c ) { int t; // // A by itself is sorted. // // Is (A,B) sorted? Not if B < A. // if ( b < a ) { t = a; a = b; b = t; } // // Is (A,B,C) sorted? Not if C < B. In that case, we need to make a second check. // if ( c < b ) { t = b; b = c; c = t; if ( b < a ) { t = a; a = b; b = t; } } return; } void sort_vec ( int d[3] ) { int t; // // D[0] by itself is sorted. // // Is (D[0],D[1]) sorted? Not if D[1] < D[0]. // if ( d[1] < d[0] ) { t = d[0]; d[0] = d[1]; d[1] = t; } // // Is (D[0],D[1],D[2]) sorted? Not if D[2] < D[1]. In that case, we need to make a second check. // if ( d[2] < d[1] ) { t = d[1]; d[1] = d[2]; d[2] = t; if ( d[1] < d[0] ) { t = d[0]; d[0] = d[1]; d[1] = t; } } return; } void sort_3int_pointers ( int *a, int *b, int *c ) { int t; // // A by itself is sorted. // // Is (A,B) sorted? Not if B < A. // if ( *b < *a ) { t = *a; *a = *b; *b = t; } // // Is (A,B,C) sorted? Not if C < B. In that case, we need to make a second check. // if ( *c < *b ) { t = *b; *b = *c; *c = t; if ( *b < *a ) { t = *a; *a = *b; *b = t; } } return; }