是否有一个类似于qsort()的函数在内核空间中使用?

时间:2013-06-18 17:32:51

标签: c linux-kernel qsort

我正在编写一个可加载的内核模块,我需要使用显然不能在内核空间中使用的函数qsort()

我可以使用具有类似功能的功能吗?

(内核版本3.5.0)

2 个答案:

答案 0 :(得分:16)

linux内核包含一个heapsort的实现,其执行类似于quicksort。内核开发人员建议使用快速排序(在内核中)并提供以下基本原理:

  

[heapsort]的排序时间是平均和最差情况下的O(n log n)。而   qsort平均快20%左右,它可以被利用   O(n * n)最坏情况行为和额外的内存要求   它不太适合内核使用。

标题

#include <linux/sort.h>

原型

void sort(
    void *base, size_t num, size_t size,
    int (*cmp_func)(const void *, const void *),
    void (*swap_func)(void *, void *, int size));

用法

static int compare(const void *lhs, const void *rhs) {
    int lhs_integer = *(const int *)(lhs);
    int rhs_integer = *(const int *)(rhs);

    if (lhs_integer < rhs_integer) return -1;
    if (lhs_integer > rhs_integer) return 1;
    return 0;
}

void example() {
    int values[1024] = {...};
    sort(values, 1024, sizeof(int), &compare, NULL);
}

答案 1 :(得分:5)

这是一个很好的问题。 lib/sort.c中的函数sort()完成了这项工作,但这是一种堆排序,您可以在lib/sort.c

中了解有关此选择的更多信息