我使我的冒泡排序程序通用.我继续测试它,它运行良好,直到我在阵列中放置一个负数,我很惊讶它被推到最后,使它比正数更大.
显然memcmp是原因,那么为什么memcmp()负数大于正数呢?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void bubblesortA(void *_Buf, size_t bufSize, size_t bytes);
int main(void)
{
size_t n, bufsize = 5;
int buf[5] = { 5, 1, 2, -1, 10 };
bubblesortA(buf, 5, sizeof(int));
for (n = 0; n < bufsize; n++)
{
printf("%d ", buf[n]);
}
putchar('\n');
char str[] = "bzqacd";
size_t len = strlen(str);
bubblesortA(str, len, sizeof(char));
for (n = 0; n < len; n++)
{
printf("%c ", str[n]);
}
putchar('\n');
return 0;
}
void bubblesortA(void *buf, size_t bufSize, size_t bytes)
{
size_t x, y;
char *ptr = (char*)buf;
void *tmp = malloc(bytes);
for (x = 0; x < bufSize; x++)
{
ptr = (char *)buf;
for (y = 0; y < (bufSize - x - 1); y++)
{
if (memcmp(ptr, ptr + bytes, bytes) > 0)
{
memcpy(tmp, ptr, bytes);
memcpy(ptr, ptr + bytes, bytes);
memcpy(ptr + bytes, tmp, bytes);
}
ptr += bytes;
}
}
free(tmp);
}
Run Code Online (Sandbox Code Playgroud)
编辑:
那么,如何修改程序以使其正确比较?
memcmp比较字节,它不知道字节是否代表ints,doubles,字符串,...
因此,将字节视为无符号数不能做得更好.因为负整数通常使用二进制补码表示,所以设置负整数的最高位,使其大于任何正有符号整数.
回答OP的附加编辑
我怎样才能修改程序以使其正确比较?
要将两种类型作为匿名位模式进行比较,memcmp()效果很好。要比较某种类型的两个值,代码需要该类型的比较函数。以下qsort() 风格:
void bubblesortA2(void *_Buf,size_t bufSize,size_t bytes,
int (*compar)(const void *, const void *)))
{
....
// if(memcmp(ptr,ptr+bytes,bytes) > 0)
if((*compar)(ptr,ptr+bytes) > 0)
....
Run Code Online (Sandbox Code Playgroud)
要进行比较int,请传入比较int函数。请注意a,b是对象的地址。
int compar_int(const void *a, const void *b) {
const int *ai = (const int *)a;
const int *bi = (const int *)b;
return (*ai > *bi) - (*ai < *bi);
}
Run Code Online (Sandbox Code Playgroud)
要进行比较char,请传入比较char函数
int compar_int(const void *a, const void *b) {
const char *ac = (const char *)a;
const char *bc = (const char *)b;
return (*ac > *bc) - (*ac < *bc);
}
Run Code Online (Sandbox Code Playgroud)