源码如下
#include<stdio.h>
#include<stdlib.h>
#include <string.h>
typedef int (*COMPARE)(const void *begin ,const void *end) ;
int ByteSwas(void *begin,void *end ,size_t size)
{
void *temp;
if((temp = (char *)malloc(size)) == NULL)
return -1;
else
{
memcpy(temp,begin,size);
memcpy(begin,end,size);
memcpy(end,temp,size);
}
free(temp);
return 1;
}
int compare_int_up (const void *begin ,const void *end)
{
return *(int *)begin - *(int *)end;
}
int compare_int_Low(const void *begin ,const void *end)
{
return *(int *)end - *(int *)begin;
}
int compare_int_string(const void *begin ,const void *end)
{
return strcmp( *(char **)begin,*(char **)end );
}
void bubbleSort(void *abuffer,size_t nNum,size_t size,COMPARE compare)
{
int flag = 1;
int i,j;
for( i = 0;flag == 1 && i < nNum - 1;i++)
{
flag = 0;
for(j = 0 ;j < nNum - 1 ;j++)
{
void *pdate = (unsigned char*)abuffer + j*(size);
void *pdate1 = (unsigned char*)abuffer + j*(size+1);
if(compare(pdate,pdate1)>0)
{
ByteSwas(pdate,pdate1,size);
flag = 1;
}
}
}
}
int main(void)
{
int arrayInt[] = { 39, 33, 18, 64, 73, 30, 49, 51, 81 };
int numArray = sizeof(arrayInt) / sizeof(arrayInt[0]);
int i;
bubbleSort(arrayInt, numArray, sizeof(arrayInt[0]), compare_int_up);
for ( i = 0; i <numArray; i++) {
printf("%d ", arrayInt[i]);
}
printf("\n");
bubbleSort(arrayInt, numArray, sizeof(arrayInt[0]), compare_int_Low);
for ( i = 0; i <numArray; i++) {
printf("%d ", arrayInt[i]);
}
printf("\n");
char * arrayStr[] = { "Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday" };
numArray = sizeof(arrayStr) / sizeof(arrayStr[0]);
bubbleSort(arrayStr, numArray, sizeof(arrayStr[0]), compare_int_string);
for ( i = 0; i < numArray; i++)
{
printf("%s\n", arrayStr[i]);
}
}
问题排查
void *pdate = (unsigned char*)abuffer + j*(size);
void *pdate1 = (unsigned char*)abuffer + j*(size+1);
正确代码
void *pdate = (unsigned char*)abuffer + size*(j);
void *pdate1 = (unsigned char*)abuffer + size*(j+1);