Let's go!!!!!
分类: LINUX
2014-12-07 00:25:35
main.c函数
#include
#include "sort.h"
int main()
{
int array[NUM] = {9,0,7,1,5,4};
int i = 0;
printf("Before sort:\n");
for(i=0;i
printf("%d ",array[i]);
printf("\n");
issort(array,NUM,sizeof(int),cmp);
printf("After sort:\n");
for(i=0;i
printf("%d ",array[i]);
printf("\n");
}
排序函数
#include
#include
#include
#include "sort.h"
int cmp(const void *key1,const void *key2)
{
if(*(int *)key1 > *(int *)key2)
return 1;
if(*(int *)key1 < *(int *)key2)
return -1;
if(*(int *)key1 == *(int *)key2)
return -1;
}
int issort(void *data,int size,int esize,Compare cmp)
{
char *a = data;
void *key;
int i = 0;
int j = 0;
if((key = (char *)malloc(esize)) == NULL)
return -1;
for(j = 1;j < size; j++)
{
memcpy(key,&a[j * esize],esize);
i = j - 1;
while(i >= 0 && cmp(&a[i * esize],key) > 0)
{
memcpy(&a[(i + 1) * esize],&a[i * esize],esize);
i--;
}
memcpy(&a[(i+1) * esize],key,esize);
}
free(key);
return 0;
}
头文件
#ifndef __SORT_H
#define __SORT_H
#define NUM 6
typedef int (*Compare)(const void *key1,const void *key2);
int issort(void *data,int size,int esize,Compare cmp);
int cmp(const void *key1,const void *key2);
#endif
Makefile
main:main.o sort.o
cc -o main main.o sort.o
main.o:main.c sort.h
cc -c main.c
sort.o:sort.c sort.h
cc -c sort.c
clean:
rm *.o -rf