Chinaunix首页 | 论坛 | 博客
  • 博客访问: 153820
  • 博文数量: 32
  • 博客积分: 2053
  • 博客等级: 大尉
  • 技术积分: 382
  • 用 户 组: 普通用户
  • 注册时间: 2010-04-09 12:45
文章分类

全部博文(32)

文章存档

2011年(12)

2010年(20)

分类: LINUX

2011-02-09 10:02:24

实现一个C的通用排序函数,可以对int,struct,float等进行排序

#include <stdio.h>
struct point
{
        int a;
        int b;
};
struct point a[] = {{3,56}, {6,1}, {3, 57}, {100, 2}, {0, 9}};
int sort(void *start, int n, int len, int (*compare)(void*, void *))
{
        int i, j, max, k;
        char *p1, *p2;
        for(i = 0; i <= n-2; i++)
        {
                max = i;
                for(j = i+1; j <= n-1; j++)
                {
                        if(compare(start + max * len, start + j * len) < 0)
                        {
                                max = j;
                        }
                }
                if(max == i)
                        continue;

                p1 = start + i * len;
                p2 = start + max * len;
                for(k = 0; k < len; k++)
                {
                        *p1 = *p1 ^ *p2;
                        *p2 = *p1 ^ *p2;
                        *p1 = *p1 ^ *p2;
                        p1++;
                        p2++;
                }
        }
}
int compare(void *p1, void *p2)
{
        struct point a = *(struct point*)p1, b = *(struct point*)p2;
        if(a.a > b.a || (a.a == b.a && a.b > b.b))
                return 1;
        else if(a.a == b.a && a.b == b.b)
                return 0;
        else
                return -1;
}
/*
int compare(void *p1, void *p2)
{
        int a = *(int*)p1, b = *(int*)p2;
        if(a > b)
                return 1;
        else if(a == b)
                return 0;
        else
                return -1;
}
*/

int main()
{
        sort(a, 5, 8, compare);
        int i;
        for(i = 0; i < 5; i++)
        printf("%d %d\n", a[i].a, a[i].b);
}

总结
1.通用的函数中所有的指针都使用void*,通过一个给定的长度len来进行++操作
2.在特定实现的部分通过对指针进行强转来操作。这些函数的定义都是使用void*,内部进行转化
阅读(1795) | 评论(0) | 转发(1) |
0

上一篇:小记

下一篇:有序数组的合并

给主人留下些什么吧!~~