Chinaunix首页 | 论坛 | 博客
  • 博客访问: 231071
  • 博文数量: 68
  • 博客积分: 40
  • 博客等级: 民兵
  • 技术积分: 355
  • 用 户 组: 普通用户
  • 注册时间: 2011-03-25 11:49
文章分类
文章存档

2014年(2)

2012年(66)

分类:

2012-04-24 17:52:06

原文地址:c 通用排序 作者:xunuj

实现一个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*,内部进行转化
阅读(747) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~