H
herrcho
#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 */
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 */
memcpy((char *)base + i*width, min, width); /* a = 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.. ^^
#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 */
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 */
memcpy((char *)base + i*width, min, width); /* a = 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.. ^^