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 strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Search and Sort in an array

Status
Not open for further replies.

Tchriss99

Programmer
Dec 31, 2002
2
GB
I have an array which is as follows:

1 2 8
-1 -2 3
-1 1 4
-2 -1 2

I wan to do a search for the smallest value according to the last column. IOW I want to select 2 and return the values -2,-1.

Thanks for the help.
 
Convert this double array into single one, so you have it like this:

1 2 8 -1 -2 3 -1 1 4 -2 -1 2

then sort it the way one would sort one dimensional array, picking 2 last elements if its going to be descending. Best Regards,

aphrodita@mail.krovatka.ru {uiuc rules}
 
No need to convert to a one-dimensional array, surely. Plus that might obscure the purpose of the array.

Here's a simple treatment.

int myarray[ NOROWS ][ NOCOLS ];

getvalues( int* p1, int* p2 )
{
int row, returnrow, minvalue;

row = 0;
*p1 = myarray[ row ][ 0 ];
*p2 = myarray[ row ][ 1 ];
minvalue = myarray[ row ][ 2 ];

for( row = 1; row < NOROWS; row++ )
{
if( minvalue > myarray[ row ][ 2 ] )
{
*p1 = myarray[ row ][ 0 ];
*p2 = myarray[ row ][ 1 ];
minvalue = myarray[ row ][ 2 ];
}
}
}

Best wishes,

tootired
 
The problem is sorting the 2-dim array, which your treatment does not show. Converting it to 1-dim, sorting, converting back is a solution that does not require much manipulation. Best Regards,

aphrodita@mail.krovatka.ru {uiuc rules}
 
I think we're answering different questions! My reading of the original question is that we don't want to sort the whole array - we want to find the minimum value in the third column, and then return the corresponding values in the first two columns.

The example given is that the &quot;lookup&quot; value is 2, and the returned values are -1, -2. Your sorting approach leaves two -2 values.

So IMHO my answer is right, and your answer is right to the question &quot;I've got a two dimensional array and I want to know the lowest 2 values held in it&quot;.

Happy New Year!

tootired
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top