【发布时间】:2015-02-19 07:26:45
【问题描述】:
请允许我使用一个示例(在 Java 中)更具体。
假设你要对这个数组进行排序:
[10, 20, 30, 40, 50, 60, 70, 80, 90]
让我们假设枢轴是值 30。排序后它应该是这样的:
[40, 50, 60, 70, 80, 90, 30, 10, 20]
大于 30 的数字在 30 的左侧结束(但仍按从小到大排序),小于 30 的数字在 30 的右侧(但仍按从小到大排序)。
注意:假设数据集很大,不一定要这个精确的数组集。
现在这是我提出的算法(以伪代码形式):
1). Count how many values are more than 30, call this count value 'X'. Swap the value of 30 at index X.
2). Have 2 "movers" that start on both ends, each moving towards the pivot and determining which numbers should go on what side
3). Use bubble sort on both sides of the pivot to finish the algorithm.
现在,这是我自己算法的问题。在我进行冒泡排序之前,它是 O(n),这使得它成为 O(n^2)。
我的具体问题是:什么是更好的方法,并且仍然保持 O(n)?或者如果可能的话 O(log n) ?答案可以是伪代码,但您选择为答案编写代码,我更喜欢用 Java 编写。
注意:该数组是一个整数数组。都有独特的价值。
编辑:合并排序显然是比冒泡排序更好的解决方案。我的问题实际上是针对寻找 O(n) 或 O(log n) 解决方案。
【问题讨论】:
-
获取 Donald E. Knuth 的书“计算机编程的艺术”,第 3 卷 - 排序和搜索。它会回答你所有的问题。
标签: java arrays algorithm sorting