【问题标题】:finding the middle value without sorting [duplicate]在不排序的情况下找到中间值[重复]
【发布时间】:2011-10-31 21:30:05
【问题描述】:

可能重复:
How to find the kth largest element in an unsorted array of length n in O(n)?

是否有任何算法可以在不执行排序操作的情况下找到给定列表的中间值。

例如,如果列表保持为堆栈并包含 (1,2,5,3,4,6),则中间值应为 4 所以我的问题是如何在不对列表执行排序操作的情况下获得这个值。

这可能吗?

【问题讨论】:

  • 为什么不想对列表进行排序? 好奇
  • 如何计算中间值?据我所知,在您的示例中可能是 3 或 4。
  • 为什么4是中间值?这是 3 和 4 的平均值吗?
  • 可能 OP 只想要中位数。大多数排序都是 nlogn,但也有接近线性的算法。并不是说它们一定更快,但它们很有趣。
  • 我做了排序所以得到 1 2 3 4 5 6 然后 mid=list[size()/2+1] 等于 4

标签: java algorithm data-structures


【解决方案1】:

是的,有一些众所周知的算法可以找到列表的第 k 个最大元素。见How to find the kth largest element in an unsorted array of length n in O(n)?

这里k 被预先计算为length/2 当然,如果列表中有偶数个元素,则调整为最接近的整数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-03
    • 1970-01-01
    • 1970-01-01
    • 2014-04-05
    相关资源
    最近更新 更多