MST

星途 面试题库

面试题:C语言函数指针专家难度题目

编写一个通用的排序函数 `void mySort(void *arr, int size, int elementSize, int (*compare)(const void *, const void *))`,该函数使用函数指针 `compare` 来比较数组元素。然后定义两个比较函数,一个用于比较 `int` 类型数组使其升序排列,另一个用于比较 `double` 类型数组使其降序排列。并在 `main` 函数中分别对 `int` 数组和 `double` 数组调用 `mySort` 函数进行排序并打印结果。要求充分考虑不同数据类型的内存操作和指针运算。
49.1万 热度难度
编程语言C

知识考点

AI 面试

面试题答案

一键面试
#include <stdio.h>
#include <stdlib.h>

// 比较函数,用于int类型升序
int compareIntAsc(const void *a, const void *b) {
    return (*(int *)a - *(int *)b);
}

// 比较函数,用于double类型降序
int compareDoubleDesc(const void *a, const void *b) {
    return (*(double *)b - *(double *)a);
}

// 通用排序函数
void mySort(void *arr, int size, int elementSize, int (*compare)(const void *, const void *)) {
    char *base = (char *)arr;
    for (int i = 0; i < size - 1; ++i) {
        for (int j = 0; j < size - i - 1; ++j) {
            char *curr = base + j * elementSize;
            char *next = base + (j + 1) * elementSize;
            if (compare(curr, next) > 0) {
                char temp[elementSize];
                for (int k = 0; k < elementSize; ++k) {
                    temp[k] = curr[k];
                    curr[k] = next[k];
                    next[k] = temp[k];
                }
            }
        }
    }
}

int main() {
    int intArr[] = {5, 3, 7, 1, 9};
    int intSize = sizeof(intArr) / sizeof(intArr[0]);
    mySort(intArr, intSize, sizeof(int), compareIntAsc);
    printf("Sorted int array (ascending): ");
    for (int i = 0; i < intSize; ++i) {
        printf("%d ", intArr[i]);
    }
    printf("\n");

    double doubleArr[] = {5.5, 3.3, 7.7, 1.1, 9.9};
    int doubleSize = sizeof(doubleArr) / sizeof(doubleArr[0]);
    mySort(doubleArr, doubleSize, sizeof(double), compareDoubleDesc);
    printf("Sorted double array (descending): ");
    for (int i = 0; i < doubleSize; ++i) {
        printf("%lf ", doubleArr[i]);
    }
    printf("\n");

    return 0;
}