Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Two Dimensional array sort 1

Status
Not open for further replies.

rgarro

IS-IT--Management
Aug 7, 2002
5
US
How do you sort a 2 dimensional array???
 
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
}

 
Thank you very much for your time...it is much appreciated.
 
No prob.

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?
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top