449,107 Members | 1,103 Online
Need help? Post your question and get tips & solutions from a community of 449,107 IT Pros & Developers. It's quick & easy.

# sorting 2d arrays using qsort

 P: n/a hai this is my 2d array. int a[][6] = { {5,2,20,1,30,10}, {23,15,7,9,11,3}, {40,50,34,24,14,4}, {9,10,11,12,13,14}, {31,4,18,8,27,17}, {44,32,13,19,41,19}, {1,2,3,4,5,6}, {80,37,47,18,21,9} }; after for(i=0;i
23 Replies

 P: n/a > return ( *(int*)a - *(int*)b); That's a dangerous way to compare two signed integers. You're risking underflow, which is undefined. now i want to sort each row of elements for above array You can't do it with qsort because qsort tries to directly exchange two items; an operation that arrays don't support. You can, however, create an array of pointers to int, point them to each array in a, and then sort that array by writing another comparison function that compares the first mismatch in the two arrays being compared: #include #include static int arraya[][6] = { {5,2,20,1,30,10}, {23,15,7,9,11,3}, {40,50,34,24,14,4}, {9,10,11,12,13,14}, {31,4,18,8,27,17}, {44,32,13,19,41,19}, {1,2,3,4,5,6}, {80,37,47,18,21,9} }; static int *arrayb[8]; int cmp_int(const void *a,const void *b) { const int *ia = a; const int *ib = b; if (*ia < *ib) return -1; else if (*ia > *ib) return +1; else return 0; } int cmp_array(const void *a, const void *b) { const int **ia = a; const int **ib = b; int i, cmp; for (i = 0; i < 6; i++) { if ((cmp = cmp_int(&(*ia)[i], &(*ib)[i])) != 0) return cmp; } return 0; } int main(void) { int i, j; for (i = 0; i < 8; i++) qsort(arraya[i], 6, sizeof(int), cmp_int); for (i = 0; i < 8; i++) { for (j = 0; j < 6; j++) printf("%4d", arraya[i][j]); printf("\n"); } printf("\n"); for (i = 0; i < 8; i++) arrayb[i] = arraya[i]; qsort(arrayb, 8, sizeof(int*), cmp_array); for (i = 0; i < 8; i++) { for (j = 0; j < 6; j++) printf("%4d", arrayb[i][j]); printf("\n"); } printf("\n"); } Nov 14 '05 #2

 P: n/a On Sat, 11 Jun 2005 05:35:06 -0700, yatindran wrote: hai this is my 2d array. int a[][6] = { {5,2,20,1,30,10}, {23,15,7,9,11,3}, {40,50,34,24,14,4}, {9,10,11,12,13,14}, {31,4,18,8,27,17}, {44,32,13,19,41,19}, {1,2,3,4,5,6}, {80,37,47,18,21,9} }; after for(i=0;ib); } where dim=6, i get the foll o/p: 1 2 5 10 20 30 3 7 9 11 15 23 4 14 24 34 40 50 9 10 11 12 13 14 4 8 17 18 27 31 13 19 19 32 41 44 1 2 3 4 5 6 9 18 21 37 47 80 (works fine!) OK, you're sorting the contents each row individually which is fine. now i want to sort each row of elements for above array, like 1 2 3 4 5 6 1 2 5 10 20 30 ... etc. what is the qsort routine and function, can anybody help me ? You just have to remember that the array a is simply an array of elements where each of those elements is itself an array, so you can write: qsort(a, sizeof a/sizeof *a, sizeof *a, compare_rows); Where sizeof a/sizeof *a is the number of rows in a, sizeof *a is the size in bytes of a row. The comparison function would be something like static int compare_rows(const void *va, const void *vb) { const int *pa = *(const int (*)[6])va; const int *pb = *(const int (*)[6])vb; int i; for (i = 0; i < 6; i++) { if (pa[i] != pb[i]) return (pa[i] > pb[i]) ? 1 : -1; } return 0; } Lawrence Nov 14 '05 #3

 P: n/a On Sat, 11 Jun 2005 07:27:29 -0700, James Daughtry wrote: return ( *(int*)a - *(int*)b); That's a dangerous way to compare two signed integers. You're risking underflow, which is undefined. now i want to sort each row of elements for above array You can't do it with qsort because qsort tries to directly exchange two items; an operation that arrays don't support. C doesn't directly supply an exchange operation for any type, arrays are no different in this respect. In fact there is nothing in the definition of qsort() that requires it to use exchanges as such, although many common sorting algorithms do use them. The more fundamental operation is a copy. qsort() doesn't know or care about the type of the elements of the array it is sorting, in particular it doesn't care whether they are are themselves arrays or not. In C you can copy (and therefore exchange a pair of) ANY object by treating it as an array of sizeof(object) bytes (specifically an array of unsigned char). An implementation of qsort() is likely to use memcpy() or something equivalent for copying which works fine on arrays. All it needs to do this is a pointer to the object and the size of the object in bytes. All the necessary information is passed in qsort()'s arguments. You can, however, create an array of pointers to int, point them to each array in a, and then sort that array by writing another comparison function that compares the first mismatch in the two arrays being compared: You can do that, and there may be efficiency advantages to doing so (i.e. copying a pointer is likely to be quicker than copying a row), but you don't have to. Lawrence Nov 14 '05 #4

 P: n/a > An implementation of qsort() is likely to use memcpy() or something equivalent for copying which works fine on arrays. True, but can that be relied on to portably sort a two dimensional array as you suggested? Nov 14 '05 #5

 P: n/a On Sat, 11 Jun 2005 12:02:34 -0700, James Daughtry wrote: An implementation of qsort() is likely to use memcpy() or something equivalent for copying which works fine on arrays. True, but can that be relied on to portably sort a two dimensional array as you suggested? Yes. There's nothing that makes arrays different to any other type of object for the purposes of qsort(). Remember again that the implementation of qsort() knows nothing about the type of the data being sorted - C doesn't have any form of runtime type information. More fundamentally there is noting in the standard's specification of qsort() that precludes it from sorting arrays whose elements are themselves arrays. Lawrence Nov 14 '05 #6

 P: n/a Lawrence Kirby wrote: On Sat, 11 Jun 2005 12:02:34 -0700, James Daughtry wrote: An implementation of qsort() is likely to use memcpy() or something equivalent for copying which works fine on arrays. True, but can that be relied on to portably sort a two dimensional array as you suggested? Yes. There's nothing that makes arrays different to any other type of object for the purposes of qsort(). Remember again that the implementation of qsort() knows nothing about the type of the data being sorted - C doesn't have any form of runtime type information. More fundamentally there is noting in the standard's specification of qsort() that precludes it from sorting arrays whose elements are themselves arrays. Except you have to decide and codify what makes A1 > A2, or A1 < A2, or A1 == A2. -- "If you want to post a followup via groups.google.com, don't use the broken "Reply" link at the bottom of the article. Click on "show options" at the top of the article, then click on the "Reply" at the bottom of the article headers." - Keith Thompson Nov 14 '05 #7

 P: n/a On Sat, 11 Jun 2005 22:21:45 +0000, CBFalconer wrote: Lawrence Kirby wrote: .... More fundamentally there is noting in the standard's specification of qsort() that precludes it from sorting arrays whose elements are themselves arrays. Except you have to decide and codify what makes A1 > A2, or A1 < A2, or A1 == A2. As you do with any type of array element. Lawrence Nov 14 '05 #8

 P: n/a ya*******@gmail.com wrote: hai this is my 2d array. int a[][6] = { {5,2,20,1,30,10}, {23,15,7,9,11,3}, {40,50,34,24,14,4}, {9,10,11,12,13,14}, {31,4,18,8,27,17}, {44,32,13,19,41,19}, {1,2,3,4,5,6}, {80,37,47,18,21,9} }; after for(i=0;i #include int int_comp(const void *a, const void *b); int a6int_comp(const void *a, const void *b); int main(void) { int a[][6] = { {5,2,20,1,30,10}, {23,15,7,9,11,3}, {40,50,34,24,14,4}, {9,10,11,12,13,14}, {31,4,18,8,27,17}, {44,32,13,19,41,19}, {1,2,3,4,5,6}, {80,37,47,18,21,9} }; const size_t dim = sizeof *a / sizeof **a; const size_t box = sizeof a / sizeof *a; size_t i, j; puts("\n/* BEGIN new.c output */\n"); for (i = 0; i != box; ++i) { for (j = 0; j != dim; ++j) { printf("%d ", a[i][j]); } putchar('\n'); } putchar('\n'); for (i = 0; i != box; ++i) { qsort(a[i], dim, sizeof *a[i], int_comp); } for (i = 0; i != box; ++i) { for (j = 0; j != dim; ++j) { printf("%d ", a[i][j]); } putchar('\n'); } putchar('\n'); qsort(a, box, sizeof *a, a6int_comp); for (i = 0; i != box; ++i) { for (j = 0; j != dim; ++j) { printf("%d ", a[i][j]); } putchar('\n'); } puts("\n/* END new.c output */"); return 0; } int int_comp(const void *a, const void *b) { return *(int *)b > *(int *)a ? -1 : *(int *)b != *(int *)a; } int a6int_comp(const void *a, const void *b) { size_t n; const int *a_ptr = a; const int *b_ptr = b; for (n = 0; n != 6; ++n) { if (b_ptr[n] > a_ptr[n]) { return -1; } if (a_ptr[n] > b_ptr[n]) { return 1; } } return 0; } /* END new.c */ -- pete Nov 14 '05 #9

 P: n/a Lawrence Kirby wrote: In C you can copy (and therefore exchange a pair of) ANY object by treating it as an array of sizeof(object) bytes (specifically an array of unsigned char). /* BEGIN new.c */ #include void swap(void *s1, void *s2, size_t n); int main(void) { char odd[] = "1 3 5 7 9"; char even[] = "0 2 4 6 8"; double three = 3.0; double four = 4.0; swap(&odd, &even, sizeof odd); printf("odd %s\n", odd); printf("even %s\n", even); swap(&three, &four, sizeof three); printf("three %f\n", three); printf("four %f\n", four); return 0; } void swap(void *s1, void *s2, size_t n) { unsigned char *p1, *p2, *end, temp; p1 = s1; p2 = s2; end = p2 + n; do { temp = *p1; *p1++ = *p2; *p2++ = temp; } while (p2 != end); } /* END new.c */ -- pete Nov 14 '05 #10

 P: n/a Lawrence Kirby wrote: On Sat, 11 Jun 2005 22:21:45 +0000, CBFalconer wrote: Lawrence Kirby wrote: ... More fundamentally there is noting in the standard's specification of qsort() that precludes it from sorting arrays whose elements are themselves arrays. Except you have to decide and codify what makes A1 > A2, or A1 < A2, or A1 == A2. As you do with any type of array element. Of course. But most users are used to simply comparing basic types, or at worst passing things to strcmp. Here they might have to think about the meaning of things. -- "If you want to post a followup via groups.google.com, don't use the broken "Reply" link at the bottom of the article. Click on "show options" at the top of the article, then click on the "Reply" at the bottom of the article headers." - Keith Thompson Nov 14 '05 #11

 P: n/a pete wrote: .... snip ... int a6int_comp(const void *a, const void *b) { size_t n; const int *a_ptr = a; const int *b_ptr = b; for (n = 0; n != 6; ++n) { if (b_ptr[n] > a_ptr[n]) { return -1; } if (a_ptr[n] > b_ptr[n]) { return 1; } } return 0; } In other words you have come to the arbitrary decision that the highest indexed component of the array is the most significant. Fine, but you should document it in the comparison routine. Whether or not this is what the OP wants is unknown. -- "If you want to post a followup via groups.google.com, don't use the broken "Reply" link at the bottom of the article. Click on "show options" at the top of the article, then click on the "Reply" at the bottom of the article headers." - Keith Thompson Nov 14 '05 #12

 P: n/a CBFalconer wrote: pete wrote: ... snip ... int a6int_comp(const void *a, const void *b) { size_t n; const int *a_ptr = a; const int *b_ptr = b; for (n = 0; n != 6; ++n) { if (b_ptr[n] > a_ptr[n]) { return -1; } if (a_ptr[n] > b_ptr[n]) { return 1; } } return 0; } In other words you have come to the arbitrary decision that the highest indexed component of the array is the most significant. I don't understand what you mean. Fine, but you should document it in the comparison routine. Whether or not this is what the OP wants is unknown. OP gave an example of what he wanted. You snipped it: now i want to sort each row of elements for above array, like 1 2 3 4 5 6 1 2 5 10 20 30 ... etc. /* BEGIN new.c output */ 5 2 20 1 30 10 23 15 7 9 11 3 40 50 34 24 14 4 9 10 11 12 13 14 31 4 18 8 27 17 44 32 13 19 41 19 1 2 3 4 5 6 80 37 47 18 21 9 1 2 5 10 20 30 3 7 9 11 15 23 4 14 24 34 40 50 9 10 11 12 13 14 4 8 17 18 27 31 13 19 19 32 41 44 1 2 3 4 5 6 9 18 21 37 47 80 1 2 3 4 5 6 1 2 5 10 20 30 3 7 9 11 15 23 4 8 17 18 27 31 4 14 24 34 40 50 9 10 11 12 13 14 9 18 21 37 47 80 13 19 19 32 41 44 /* END new.c output */ -- pete Nov 14 '05 #13

 P: n/a pete wrote: CBFalconer wrote: pete wrote: ... snip ... int a6int_comp(const void *a, const void *b) { size_t n; const int *a_ptr = a; const int *b_ptr = b; for (n = 0; n != 6; ++n) { if (b_ptr[n] > a_ptr[n]) { return -1; } if (a_ptr[n] > b_ptr[n]) { return 1; } } return 0; } In other words you have come to the arbitrary decision that the highest indexed component of the array is the most significant. I don't understand what you mean. Fine, but you should document it in the comparison routine. Whether or not this is what the OP wants is unknown. OP gave an example of what he wanted. You snipped it: now i want to sort each row of elements for above array, like 1 2 3 4 5 6 1 2 5 10 20 30 ... etc. So he did. However, a decision has been made as to the relative significance of the components. Notice that the opposite decision, based on the highest order component of the array, would have given the same result as far as his example actually went. So would an array sort based on the 3rd (index 2) item of each array. Which is not a criticism of your comparison function, but simply pointing out the arbitrariness of the decisions taken. This sort of thing will always come up when comparing arrays or structs, while there is instinctive agreement on the meaning of comparison between numbers or strings. For strings, the standard spells it out anyway. -- "If you want to post a followup via groups.google.com, don't use the broken "Reply" link at the bottom of the article. Click on "show options" at the top of the article, then click on the "Reply" at the bottom of the article headers." - Keith Thompson Nov 14 '05 #14

 P: n/a CBFalconer wrote: pete wrote: CBFalconer wrote: pete wrote: ... snip ... int a6int_comp(const void *a, const void *b) { size_t n; const int *a_ptr = a; const int *b_ptr = b; for (n = 0; n != 6; ++n) { if (b_ptr[n] > a_ptr[n]) { return -1; } if (a_ptr[n] > b_ptr[n]) { return 1; } } return 0; } In other words you have come to the arbitrary decision that the highest indexed component of the array is the most significant. I don't understand what you mean. Fine, but you should document it in the comparison routine. Whether or not this is what the OP wants is unknown. OP gave an example of what he wanted. You snipped it:> now i want to sort each row of elements for above array,> like> 1 2 3 4 5 6> 1 2 5 10 20 30> ...> etc. So he did. However, a decision has been made as to the relative significance of the components. Notice that the opposite decision, based on the highest order component of the array, would have given the same result as far as his example actually went. I still don't understand. int a6int_comp(const void *a, const void *b) { size_t n; const int *a_ptr = a; const int *b_ptr = b; n = 6; while (n-- != 0) { if (b_ptr[n] > a_ptr[n]) { return 1; } if (a_ptr[n] > b_ptr[n]) { return -1; } } return 0; } gives: 9 18 21 37 47 80 4 14 24 34 40 50 13 19 19 32 41 44 4 8 17 18 27 31 1 2 5 10 20 30 3 7 9 11 15 23 9 10 11 12 13 14 1 2 3 4 5 6 int a6int_comp(const void *a, const void *b) { size_t n; const int *a_ptr = a; const int *b_ptr = b; n = 6; while (n-- != 0) { if (b_ptr[n] > a_ptr[n]) { return -1; } if (a_ptr[n] > b_ptr[n]) { return 1; } } return 0; } gives : 1 2 3 4 5 6 9 10 11 12 13 14 3 7 9 11 15 23 1 2 5 10 20 30 4 8 17 18 27 31 13 19 19 32 41 44 4 14 24 34 40 50 9 18 21 37 47 80 So would an array sort based on the 3rd (index 2) item of each array. I think I understand that, but that would be silly. Which is not a criticism of your comparison function, but simply pointing out the arbitrariness of the decisions taken. This sort of thing will always come up when comparing arrays or structs, while there is instinctive agreement on the meaning of comparison between numbers or strings. For strings, the standard spells it out anyway. What do you mean about strings? -- pete Nov 14 '05 #15

 P: n/a pete wrote: CBFalconer wrote: .... snip ... So would an array sort based on the 3rd (index 2) item of each array. I think I understand that, but that would be silly. Why? It depends on the needs. For an example we have some device out there reporting its position through a gray code encoder. For each position it reports a magnitude. We collect a herd of these, and the cycle of positions is one of the arrays in your 2d array. Its sequence goes 000, 001, 011, 111, 110, 100 (ok, so its not a proper gray, but only one bit changes at a time avoiding gross errors). We use these as index values into the array. Now we want so treat those arrays as attaching greater importance to the earlier entry. Write the comparison function. We can complicate it further by saying the magnitudes stored in the arrays are also gray encoded. This is a quite reasonable thing to do, in order to avoid major errors due to race conditions between bits. -- "If you want to post a followup via groups.google.com, don't use the broken "Reply" link at the bottom of the article. Click on "show options" at the top of the article, then click on the "Reply" at the bottom of the article headers." - Keith Thompson Nov 14 '05 #16

 P: n/a CBFalconer wrote: pete wrote: CBFalconer wrote: ... snip ... So would an array sort based on the 3rd (index 2) item of each array. I think I understand that, but that would be silly. Why? I don't that think OP's specifications are as cryptic as you seem to think that they are. -- pete Nov 14 '05 #17

 P: n/a pete wrote: CBFalconer wrote: pete wrote: CBFalconer wrote: ... snip ...> So would an> array sort based on the 3rd (index 2) item of each array. I think I understand that, but that would be silly. Why? I don't think that think OP's specifications are as cryptic as you seem to think that they are. -- pete Nov 14 '05 #18

 P: n/a pete wrote: pete wrote: CBFalconer wrote: pete wrote: > CBFalconer wrote: > ... snip ... > >> So would an >> array sort based on the 3rd (index 2) item of each array. > > I think I understand that, but that would be silly. Why? I don't think that OP's specifications are as cryptic as you seem to think that they are. There were about one or two typos. -- pete Nov 14 '05 #19

 P: n/a pete wrote: CBFalconer wrote: pete wrote: CBFalconer wrote: ... snip ... So would an array sort based on the 3rd (index 2) item of each array. I think I understand that, but that would be silly. Why? I don't that think OP's specifications are as cryptic as you seem to think that they are. Probably not, but I could write a lot of software that would meed the specs and be totally useless. This sort of thing leads to lawsuits and other things that enhance the lawyers standard of living. And all I really said in the first place was "document what you wrote". -- "If you want to post a followup via groups.google.com, don't use the broken "Reply" link at the bottom of the article. Click on "show options" at the top of the article, then click on the "Reply" at the bottom of the article headers." - Keith Thompson Nov 14 '05 #20

 P: n/a CBFalconer wrote: pete wrote: CBFalconer wrote: pete wrote: CBFalconer wrote: ... snip ...> So would an> array sort based on the 3rd (index 2) item of each array. I think I understand that, but that would be silly. Why? I don't that think OP's specifications are as cryptic as you seem to think that they are. Probably not, but I could write a lot of software that would meed the specs and be totally useless. This sort of thing leads to lawsuits and other things that enhance the lawyers standard of living. You're becoming Nilgean. And all I really said in the first place was "document what you wrote". No, it was really strange. If you're going to use quotes, quote what you wrote. You said "In other words you have come to the arbitrary decision that the highest indexed component of the array is the most significant. Fine, but you should document it in the comparison routine. Whether or not this is what the OP wants is unknown." Now we both know that I can't document an arbitrary decision that the highest indexed component of the array is the most significant, because there's nothing like that going on anywhere. Then you went on to say, "Notice that the opposite decision, based on the highest order component of the array, would have given the same result as far as his example actually went." .... and since there's no way that that method could produce this: 1 2 3 4 5 6 1 2 5 10 20 30 ... etc. from this: 1 2 5 10 20 30 3 7 9 11 15 23 4 14 24 34 40 50 9 10 11 12 13 14 4 8 17 18 27 31 13 19 19 32 41 44 1 2 3 4 5 6 9 18 21 37 47 80 (works fine!) .... what that tells me mostly, is just simply that you are confused and didn't understand the problem to begin with. -- pete Nov 14 '05 #21

 P: n/a On Tue, 14 Jun 2005 00:44:10 GMT, pete wrote: CBFalconer wrote: pete wrote: > > I don't that think OP's specifications are as cryptic > as you seem to think that they are. Probably not, but I could write a lot of software that would meed the specs and be totally useless. This sort of thing leads to lawsuits and other things that enhance the lawyers standard of living.You're becoming Nilgean. Don't use that term too lightly. Nilges would have written a 500+ line article claiming the poster is guilty of imperialism and how the poster is actually an unknowing minion (brainwashed by George Lucas) in a dark scheme of shady neocon agents ;-) I still try to figure out his claim that favoring C over VB is actually racist. I just can't see the connection (perhaps it's better that way :-) Nov 14 '05 #22

 P: n/a Paul Mesken wrote: On Tue, 14 Jun 2005 00:44:10 GMT, pete wrote:CBFalconer wrote: pete wrote: > > I don't that think OP's specifications are as cryptic > as you seem to think that they are. Probably not, but I could write a lot of software that would meed the specs and be totally useless. This sort of thing leads to lawsuits and other things that enhance the lawyers standard of living.You're becoming Nilgean. Don't use that term too lightly. Ni shh, he greps newsfeed. never spell his name. -- pete Nov 14 '05 #23

 P: n/a pete wrote: .... snip ... You're becoming Nilgean. Savage. This means war :-) -- "If you want to post a followup via groups.google.com, don't use the broken "Reply" link at the bottom of the article. Click on "show options" at the top of the article, then click on the "Reply" at the bottom of the article headers." - Keith Thompson Nov 14 '05 #24

### This discussion thread is closed

Replies have been disabled for this discussion.