I haven't tested this yet, and I don't know if it works, but the following should give you a starting point. Pointer arithmatic (sometimes) works with 2 dimensional arrays, and I think using pointers for a traversal of the array is a bit simpler than the alternative (given the needed comparisons in the following algorithm). For clarity's sake, I've used a simple bubble sort. You can certainly find a more efficient algorithm if you're worried about performance.
int array[ size1 ][ size2 ] = ...;
int *temp,
*ptr;
for (j = 0; j < size1 * size2 - 1; j++ )
for (i = 0, ptr = &array[ 0 ][ 0 ]; //reset ptr & i
i < size1 * size2 - 1; i++ )
{
if ( *(temp = ptr) > *(++ptr) )
swap( temp, ptr ); //user defined function
}
I got to wondering about it, and I think assigning a pointer to another pointer may produce an error (cause the other pointer may get dragged along for the ride if the first pointer changes). I forget. I'm still pretty new at this.
Anyways, my new idea is this:
int temp,
*ptr;
for (j = 0; j < size1 * size2 - 1; j++ )
for (i = 0, ptr = &array[ 0 ][ 0 ]; //reset ptr & i
i < size1 * size2 - 1; i++ )
{
if ( (temp = *ptr) > *(++ptr) ) // i.e. ( n > n + 1 )
swap( temp, *ptr ); //user defined function
}
I really should sit down and try to compile some of this for my own interest. Did either of these work?
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.