473,748 Members | 8,779 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

sorting 2d arrays using qsort

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,1 7},
{44,32,13,19,41 ,19},
{1,2,3,4,5,6},
{80,37,47,18,21 ,9}
};
after
for(i=0;i<box;i ++)
qsort(a[i],dim,sizeof(int ),dim*_sort);
int dim_sort(const void *a,const void *b)
{
return ( *(int*)a - *(int*)b);
}
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!)
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 ?
cheers,
badri

Nov 14 '05 #1
23 6344
> 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 <stdio.h>
#include <stdlib.h>

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,1 7},
{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
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,1 7},
{44,32,13,19,41 ,19},
{1,2,3,4,5,6},
{80,37,47,18,21 ,9}
};
after
for(i=0;i<box;i ++)
qsort(a[i],dim,sizeof(int ),dim*_sort);
You could write this as
int dim_sort(const void *a,const void *b)
{
return ( *(int*)a - *(int*)b);
}
Be caseful, subtracting 2 ints can overflow so this isn't well defined
unless you can be sure that the difference between any 2 values in the
array is representable as an int. It would be safer not to make
assumptions like this:

int dim_sort(const void *va, const void *vb)
{
int a = *(const int *)va;
int b = *(const int *)vb;

return (a<b) ? -1 : (a>b);
}
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(co nst 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
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
> 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
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
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.c om, 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
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
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,1 7},
{44,32,13,19,41 ,19},
{1,2,3,4,5,6},
{80,37,47,18,21 ,9}
};
after
for(i=0;i<box;i ++)
qsort(a[i],dim,sizeof(int ),dim*_sort);
int dim_sort(const void *a,const void *b)
{
return ( *(int*)a - *(int*)b);

}

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!)
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 ?


/* BEGIN new.c */

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

int int_comp(const void *a, const void *b);
int a6int_comp(cons t 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,1 7},
{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(cons t 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
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 <stdio.h>

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

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

40
4317
by: Elijah Bailey | last post by:
I want to sort a set of records using STL's sort() function, but dont see an easy way to do it. I have a char *data; which has size mn bytes where m is size of the record and n is the number of records. Both these numbers are known
3
6411
by: SilverWolf | last post by:
I need some help with sorting and shuffling array of strings. I can't seem to get qsort working, and I don't even know how to start to shuffle the array. Here is what I have for now: #include <stdio.h> void main(void) { char lines; int count = 0, i;
16
3389
by: aruna | last post by:
Given a set of integers, how to write a program in C to sort these set of integers using C, given the following conditions a. Do not use arrays b. Do not use any comparison function like if/then or switch-case c. you can use pointers only d. you cannot use any of the loops either.
4
5857
by: dough | last post by:
I have a hash table with seperate chaining with a bunch of words in it. Here is my declaration: typedef struct word *word; struct word { int count; char *s; word next; };
25
11381
by: Allie | last post by:
How would I go about sorting this structure by title? typedef struct { char author; char title; char code; int hold; int loan; } LIBRARY;
4
2172
by: rushik | last post by:
Hello all, I am using structure in my program, and my aim is to sort this structure based on some optimized sorting algo. structure is struct data { int account;
10
1219
by: seyensubs | last post by:
I have the following implementations of quicksort and insertion sort: def qSort(List): if List == : return return qSort( if x< List]) + List + \ qSort( if x>=List]) def insertSort(List): for i in range(1,len(List)): value=List
7
2391
by: abracadabra | last post by:
I am reading an old book - Programming Pearls 2nd edition recently. It says, "Even though the general C++ program uses 50 times the memory and CPU time of the specialized C program, it requires just half the code and is much easier to extend to other problems." in a sorting problem of the very first chapter. I modified the codes in the answer part, ran it and found it is almost the contrary case. The qsortints.c is the C code that uses...
77
3355
by: arnuld | last post by:
1st I think of creating an array of pointers of size 100 as this is the maximum input I intend to take. I can create a fixed size array but in the end I want my array to expand at run-time to fit the size of input. I am not able to come up with anyting all all and doing: char* arr_of_pointers; seems like a completely wrong idea as this is a static array. I want to take the input and then decide how much memory I need and then malloc...
0
8828
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9367
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9243
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8241
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6795
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6073
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4869
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3309
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2780
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.