自定义任意类型排序工具

#include<stdio.h>

typedef struct Stu {
    char name[20];
    int age;
} stu;

void sort(void *base, int size, int width, int(*compare)(void *, void *));

int comp_int(const int *a, const int *b);

int comp_double(const double *a, const double *b);

int comp_stu(const stu *a, const stu *b);


void sortInt() {
    //排序整数
    int arr[7] = {3, 4, 2, 6, 8, 9, 1};
    sort(arr, sizeof(arr) / sizeof(arr[0]), sizeof(arr[0]), comp_int);
    for (int i = 0; i < sizeof(arr) / sizeof(arr[0]); ++i) {
        printf("%d ", arr[i]);
    }
}

void sortDouble() {
    //排序浮点数
    double arrFloat[7] = {3, 4, 2, 6, 8, 9.0, 1};
    sort(arrFloat, sizeof(arrFloat) / sizeof(arrFloat[0]), sizeof(arrFloat[0]), comp_double);
    for (int i = 0; i < sizeof(arrFloat) / sizeof(arrFloat[0]); ++i) {
        printf("%f ", arrFloat[i]);
    }
}

void sortStu() {
    //排序结构体
    stu ss[3] = {{"zhang san", 100},
                 {"li si",     50},
                 {"wang wu",   60}};

    sort(ss, 3, sizeof(ss[0]), comp_stu);
    for (int i = 0; i < sizeof(ss) / sizeof(ss[0]); ++i) {
        printf("[%s,%d]\n", ss[i].name, ss[i].age);
    }
}

int main(void) {
    
//    sortInt();
//    sortDouble();
    sortStu();
    return 0;
}


int comp_int(const int *a, const int *b) {
    if (*a == *b) {
        return 0;
    } else if (*a > *b) {
        return 1;
    } else {
        return -1;
    }
}

int comp_double(const double *a, const double *b) {
    if (*a == *b) {
        return 0;
    } else if (*a > *b) {
        return 1;
    } else {
        return -1;
    }
}

int comp_stu(const stu *a, const stu *b) {
    if (a->age == b->age) {
        return 0;
    } else if (a->age > b->age) {
        return 1;
    } else {
        return -1;
    }
}

/**
 * 交换两个数的位置
 * @param p1
 * @param p2
 * @param width
 */
void swap(char *p1, char *p2, int width) {
    int i;
    for (i = 0; i < width; ++i) {
        char tmp = *(p1 + i);
        *(p1 + i) = *(p2 + i);
        *(p2 + i) = tmp;
    }
}

/**
 * 自定义排序函数,可对任意类型排序
 * @param base 待排序数组
 * @param size 数组大小
 * @param width 每个元素字节数
 * @param compare 比较大小函数
 */
void sort(void *base, int size, int width, int(*compare)(void *, void *)) {
    int i;
    int j;
    for (i = 0; i < size - 1; ++i) {
        for (j = 0; j < size - i - 1; ++j) {
            char *x = (char *) base + j * width;
            char *y = (char *) base + (j + 1) * width;
            if (compare(x, y) > 0) {
                swap(x, y, width);
            }
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值