的qsort的内部实施 [英] Internal Implementation of Qsort

查看:124
本文介绍了的qsort的内部实施的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

的qsort声明为

void qsort (void* base, size_t num, size_t size,
            int (*compar)(const void*,const void*));

我想知道怎样的qsort实现反射特性。我的意思是它是如何叫他的名字,我们传递的函数?

I want to know how does qsort implements the reflection property. I mean how does it call the function whose name we passed ?

推荐答案

的qsort 接收函数指针接收两个指针并返回 INT ,这只是它。该指针称为 COMPAR 。所有的qsort需要做的,调用这个函数是这样的:

qsort receives a pointer to function receiving two pointers and returning int, and that's just it. This pointer is called compar. All qsort needs to do to call this function is something like:

(*compar)(base+i, base+j);

其中, I Ĵ基偏移量 。它就是这么简单。你可以看到在K&放一个可能的实现; R第二版,第5.11节第120页:

Where i and j are offsets for base. It's really that simple. You can see a possible implementation in K&R second edition, section 5.11, page 120:

void qsort(void *v[], int left, int right, int (*comp)(void *, void *)) {
    int i, last;
    void swap(void *v[], int, int);

    if (left >= right)
        return;
    swap(v, left, (left + right)/2);
    last = left;
    for (i = left+1; i <= right; i++)
        if ((*comp)(v[i], v[left]) < 0) /* Here's the function call */
            swap(v, ++last, i);
    swap(v, left, last);
    qsort(v, left, last-1, comp);
    qsort(v, last+1, right, comp);
}

这篇关于的qsort的内部实施的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆