Bug in quicksort example (K&R C book)?

一个人想着一个人 提交于 2019-12-21 04:34:06

问题


This quicksort is supposed to sort "v[left]...v[right] into increasing order"; copied (without comments) from The C Programming Language by K&R (Second Edition):

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

    if (left >= right)
        return;
    swap(v, left, (left + right) / 2);
    last = left;
    for (i = left+1; i <= right; i++)
        if (v[i] < v[left])
            swap(v, ++last, i);
    swap(v, left, last);
    qsort(v, left, last-1);
    qsort(v, last+1, right);
}

I think there's a bug at

(left + right) / 2

Suppose left = INT_MAX - 1 and right = INT_MAX. Wouldn't this result in undefined behavior due to integer overflow?


回答1:


Yes, you're right. You can use left - (left - right) / 2 to avoid overflows.




回答2:


You aren't imagining an array with INT_MAX number of elements, are you?




回答3:


Yes, you're right, although it's possibly just written that way for simplicity -- it's an example after all, not production code.




回答4:


K&R was always a bit sloppy with their use of unsigned vs signed arguments. Side effect of working with a PDP that had only 16 kilobytes of memory I suppose. That's been fixed a while ago. The current definition of qsort is

void qsort(
   void *base,
   size_t num,
   size_t width,
   int (__cdecl *compare )(const void *, const void *) 
);

Note the use of size_t instead of int. And of course void* base since you don't know what kind of type you are sorting.



来源:https://stackoverflow.com/questions/6486947/bug-in-quicksort-example-kr-c-book

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!