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 Sort

Status
Not open for further replies.

logic4fun

Programmer
Apr 24, 2003
85
US
Hi all,
i am looking out for sorting a two dimensional array where i have to sort the first column of a two-column
array, and I want the second column moved along with the first one. Here is an example
24,2
36,4
18,3

should look like

18,3
24,2
36,4

so basically i want to arrange the first column in ascending order where the second column should simply move along..
Thanks in advance
Logic4Fun
 
Look at java.util.Arrays and java.lang.Comparable

-pete
 
I Want in C only as it goes with some other C program
 
Here's the "qsort" way. Depending on your data set and requirements, this may or may not be the appropriate method.

#include <stdio.h>
#include <stdlib.h>

int compare(const void *a1, const void *a2)
{
const int *array1 = a1;
const int *array2 = a2;

if (*array1 < *array2)
return -1;
else if (*array1 > *array2)
return 1;
else
return 0;
}

int main(void)
{
int i;
int array[5][2] = { { 1, 2 }, { 2, 2 }, { 0, 4}, { 15, 26 }, { 3, 9 } };

qsort(array, sizeof array / sizeof *array, sizeof *array, compare);

for (i = 0; i < sizeof array / sizeof *array; ++i)
printf(&quot;[%d][%d]\n&quot;, array[0], array[1]);
return 0;
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top