473,473 Members | 2,178 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

code Critics please..

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

void select_sort(void *base, size_t nelem, size_t width, int (*fcmp)
(const void *, const void *))
{
void *min;
int minindex;
int i,j;
min = malloc(width);

for (i = 0;i < nelem-1 ;i++ )
{
minindex = i;
memcpy(min, (char *)base + i*width, width); /* min = a[i] */
for (j=i+1; j < nelem ;j++ )
{
if (fcmp(min, (char *)base + j*width)>0 ) /* if (min >
a[j]) */
{
memcpy(min, (char *)base + j*width, width); /* min = a[j]
*/
minindex = j;
}
}
memcpy((char*) base + minindex*width, (char *)base + i*width, width);

/* a[minindex] = a[i] */

memcpy((char *)base + i*width, min, width); /* a[i] = min */
}
free(min);
}

int intcmp(const void *a, const void *b)
{
return (*(int *)a - *(int *)b);
}

int main()
{
char a[] = "wonderful";
select_sort(a,strlen(a),sizeof(char),intcmp );
puts(a);

return 0;
}

i made the above using 'Selection Sort' ..

but it outputs wrong.. it should print "deflnoruw" but just prints
"wonderful"

Could anyone explain to me ? Any comments would be appreciated.. ^^

Nov 13 '05 #1
5 1988

"herrcho" <he*********@kornet.net> wrote in message
news:bl**********@news1.kornet.net...
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void select_sort(void *base, size_t nelem, size_t width, int (*fcmp)
(const void *, const void *))
{
void *min;
int minindex;
int i,j;
min = malloc(width);

for (i = 0;i < nelem-1 ;i++ )
{
minindex = i;
memcpy(min, (char *)base + i*width, width); /* min = a[i] */
for (j=i+1; j < nelem ;j++ )
{
if (fcmp(min, (char *)base + j*width)>0 ) /* if (min >
a[j]) */
{
memcpy(min, (char *)base + j*width, width); /* min = a[j]
*/
minindex = j;
}
}
memcpy((char*) base + minindex*width, (char *)base + i*width, width);

/* a[minindex] = a[i] */

memcpy((char *)base + i*width, min, width); /* a[i] = min */
}
free(min);
}

int intcmp(const void *a, const void *b)
{
return (*(int *)a - *(int *)b);
}

int main()
{
char a[] = "wonderful";
select_sort(a,strlen(a),sizeof(char),intcmp );
puts(a);

return 0;
}

i made the above using 'Selection Sort' ..

but it outputs wrong.. it should print "deflnoruw" but just prints
"wonderful"

Could anyone explain to me ? Any comments would be appreciated.. ^^


Comments from you would be appreciated too. Whilst it is easy for you to
run through the code, it can be difficult to see your reasoning and flow of
thought. A few small comments would not go amiss and people would be more
inclined to help you.
Allan
Nov 13 '05 #2
Allan Bruce <al*****@takeawayf2s.com> wrote:
int intcmp(const void *a, const void *b)
{
return (*(int *)a - *(int *)b);
}

int main()
{
char a[] = "wonderful";
select_sort(a,strlen(a),sizeof(char),intcmp );
sizeof(char) == 1 by definition.
puts(a);

return 0;
}

i made the above using 'Selection Sort' ..

but it outputs wrong.. it should print "deflnoruw" but just prints
"wonderful"

Could anyone explain to me ? Any comments would be appreciated.. ^^


When you want to compare characters you also need to use a function to
compare characters and not ints. Now you're always comparing sets of
several characters (how many depends on sizeof(int) on your machine).
Thus you're probably also guilty of accessing memory after the end of
your 'a' array. If you replace your intcmp() function by

int charcmp(const void *a, const void *b)
{
return ( int ) ( * ( char * ) a - * ( char * ) b );
}

everything works as expected:

jens@crowley:~/TESTS> allans_selsort
deflnoruw
jens@crowley:~/TESTS>
Regards, Jens
--
_ _____ _____
| ||_ _||_ _| Je***********@physik.fu-berlin.de
_ | | | | | |
| |_| | | | | | http://www.physik.fu-berlin.de/~toerring
\___/ens|_|homs|_|oerring
Nov 13 '05 #3
herrcho wrote:
.... snip ...
int intcmp(const void *a, const void *b)
{
return (*(int *)a - *(int *)b);
}
.... snip ...
i made the above using 'Selection Sort' ..

but it outputs wrong.. it should print "deflnoruw" but just prints
"wonderful"

Could anyone explain to me ? Any comments would be appreciated.. ^^


I removed the rest, because it is very hard to read with the
overlength lines and use of excessive indentation. Don't use tabs
in your source, use spaces. Keep the line length under 72 chars.

Now to the heart of the problem - You are sorting chars, but
comparing ints! The comparison function is supplied by the caller
for a reason, only the caller knows the type of the sorted items.
So I suggest:

int intcmp(const void *a, const void *b)
{
char *ac = a; /* No extraneous casts needed */
char *bc = b;

return (*ac > *bc) - (*ac < *bc);
}

avoiding all overflows, and returning 1, 0 , -1. Works for all
integer types by simply changing the type of ac and bc.

--
Chuck F (cb********@yahoo.com) (cb********@worldnet.att.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home.att.net> USE worldnet address!
Nov 13 '05 #4
herrcho wrote:

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

void select_sort(void *base, size_t nelem, size_t width, int (*fcmp)
(const void *, const void *))
{
void *min;
int minindex;
int i,j;
unsigned char *beg = base;
unsigned char *end = beg + nelem * width; /* one elt past end of
array */
unsigned char *ith;
unsigned char *jth;
unsigned char *min;
unsigned char *tmp;
min = malloc(width);
You don't need to allocate min, but you might allocate tmp...
for (i = 0;i < nelem-1 ;i++ )
{
minindex = i;
memcpy(min, (char *)base + i*width, width); /* min = a[i] */
How about

ith = beg + i * width;
min = ith; /* POINT to the minimum element */
for (j=i+1; j < nelem ;j++ )
{
if (fcmp(min, (char *)base + j*width)>0 ) /* if (min > a[j]) */
See comments elsethread about intcmp vs charcmp.
{
memcpy(min, (char *)base + j*width, width); /* min = a[j] */
min = (unsigned char *)base + j * width;
minindex = j;
Don't need minindex.
}
}
Now that you've found the minimum element (a[m]), pointed to by min, you
can swap it with the ith element:

memcpy(tmp, ith, width); /* tmp = a[i] */
memcpy(ith, min, width); /* a[i] = a[m] */
memcpy(min, tmp, width); /* a[m] = tmp */
memcpy((char*) base + minindex*width, (char *)base + i*width, width);

/* a[minindex] = a[i] */

memcpy((char *)base + i*width, min, width); /* a[i] = min */
}
free(min);
free(tmp);
}


Also, it may be simpler to read the code if you compute pointers in your
loop statement rather than in the loop body. For example, the inner loop
might look like this:

for(jth = ith + width; jth < end; jth += width)
{
if(comp(min, jth) == 0) /* comp returns true/false */
min = jth;
}

Notice I changed fcmp to a predicate (comp). This is different than,
e.g., qsort, but a little cleaner in that the elements are ordered as
(a0,...,an) where comp(ai,ai+1) is true for i in [0..n]. (Incidentally,
you would want to change min to, e.g., kth, in the implementation to
remove the bias towards monotonically increasing sequences).

HTH,

/david

--
Andre, a simple peasant, had only one thing on his mind as he crept
along the East wall: 'Andre, creep... Andre, creep... Andre, creep.'
-- unknown
Nov 13 '05 #5
"CBFalconer" <cb********@yahoo.com> wrote in message
news:3F***************@yahoo.com...
....
Now to the heart of the problem - You are sorting chars, but
comparing ints! The comparison function is supplied by the caller
for a reason, only the caller knows the type of the sorted items.
So I suggest:

int intcmp(const void *a, const void *b)
{
char *ac = a; /* No extraneous casts needed */
char *bc = b;

return (*ac > *bc) - (*ac < *bc);
}

No casts, but it requires a diagnostic because you're discaring a const
qualifier. Making them const char * fill fix the diagnostic but it still
won't sort them properly if you prefer string characters to be sorted as
unsigned char [which is normally the case for me.]

int char_cmp(const void *a, const void *b)
{
const unsigned char *ac = a;
const unsigned char *bc = b;
return (*ac > *bc) - (*ac < *bc);
}

--
Peter
Nov 13 '05 #6

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

Similar topics

3
by: Rv5 | last post by:
I have an assignment due mid next week that I have completed. I was hoping someone could take a look at the code and tell me what they think of the style. Id like to know if this is good code...
2
by: dapgy | last post by:
Does someone have the Python code to pull just the filename and extension from the end of an absolute path please. Thanks in advance ...
1
by: Mark | last post by:
Hi all I can write basic VBA code. I have on problem, I have a tbl with the following fields: lngempID - Name - Password - IN This is for a logon form once the user logon I want the field IN to...
9
by: hope | last post by:
Hi Access 97 I'm lost on this code please can you help ================================= Below is some simple code that will concatenate a single field's value from multiple records into a...
3
by: Coby Herd | last post by:
I keep getting the error message - Error Type: Microsoft JET Database Engine (0x80004005) Unrecognized database format 'c:\inetpub\wwwroot\blog\db\blog.mdb'. /blog/admin/Default.asp, line 14 ...
2
by: matt | last post by:
this is my first program in this language ever (besides 'hello world'), can i get a code critique, please? it's purpose is to read through an input file character by character and tally the...
2
by: Wayneyh | last post by:
Hi all I am having trouble getting some code working. Would someone please check the following code and tell me why it doesn't work. If additional info is required please ask. Thanks. ...
1
by: ramyamoparthi | last post by:
<%@ page import="java.sql.*"%> <jsp:include page="home.jsp" /> <div style="left:200;top:0;height:100%;width:800;background-color:#d6d6d6;position:absolute"> <HTML> <HEAD> <TITLE> Add B.Tech...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
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...
0
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...
0
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,...
0
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...
0
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
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 ...

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.