#include <stdio.h>
#include <string.h>
#include <malloc.h>
void isort(void *base,
const size_t size,
const size_t length,
int (* comp)(const void *, const void *))
{
char * pCurElem = NULL;
char * pPreElem = NULL;
char * pTemp = (char *)malloc(size);
int index_out = 0;
int index_in = 0;
for (index_out = 1; index_out < length; ++index_out)
{
pCurElem = base + size * index_out; //当前待排序元素
memcpy(pTemp, pCurElem, size); //备份单前待排序元素值
for (index_in = index_out - 1; index_in >= 0; --index_in) //倒序遍历有序元素
{
pPreElem = base + size * index_in; //当前待比较元素
if (comp(pTemp, pPreElem) >= 0) //符合要求
{
memcpy(pPreElem + size, pTemp, size);
break;
}
memcpy(pPreElem + size, pPreElem, size);
}
if (index_in < 0)
memcpy(base, pTemp, size);
}
free(pTemp);
}
int cmp(const void *valLeft, const void *valRight)
{
return (*(int *)valLeft - *(int *)valRight);
}
int main()
{
int array[] = {3,2,4,7,5,6, 8, 1};
int index,
size = sizeof(array[0]),
length = sizeof(array)/sizeof(array[0]);
isort(array, size, length, cmp);
for (index = 0; index < length; ++index)
printf("%d\n", array[index]);
return 0;
}
11-15
11-15