You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何构造数组使glibc的qsort()达到O(n²)时间复杂度?

如何构造数组使glibc的qsort()达到O(n²)时间复杂度?

很早之前就听说qsort函数基于快速排序算法,最坏时间复杂度为O(n²)。但最近尝试构造能让qsort超时的数据时,发现其实现与常规快速排序不同,采用了诸多优化技巧。例如glibc实现中有这样的注释:

/* Select median value from among LO, MID, and HI. Rearrange
LO and HI so the three values are sorted. This lowers the
probability of picking a pathological pivot value and
skips a comparison for both the LEFT_PTR and RIGHT_PTR in
the while loops. */

我尝试过多种数组构造方式,比如升序、降序以及半升半降数组:

for (int i = 0; i < N / 2; i++)
{
    a[i] = i;
}
for (int i = N / 2; i < N; i++)
{
    a[i] = N - 1 - i;
}

还有这种奇偶分位置的构造:

for (int i = 0; i < N; i++)
{
    if (i & 1)
        a[N - 1 - i / 2] = i;
    else
        a[i / 2] = i;
}

但这些构造方式都无法触发qsort的O(n²)最坏情况。尽管我看过glibc中qsort的源码,仍想不出有效的构造方法,因此想请教:如何构造数组才能让qsort()达到O(n²)时间复杂度?

内容的提问来源于stack exchange,提问作者Sihan Lv

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 05:20:57