以O(n * Log(K))复杂度对几乎排序的数组进行排序

时间:2019-04-10 14:57:36

标签: algorithm sorting merge time-complexity complexity-theory

问题-即将排序的数组-给定一个n个元素的数组,每个元素与已排序数组中的实际位置相距最多K个位置,设计一种算法,以O(nLogK)时间排序。

Approach - I divide the array in n/K elements each(n/k + 1 , if n%k!=0).

Then I run a loop n/k times ,inside which I sort eack n/k group using 
MergeSort(Complexity = KLogK).So complexity for the loop is O(nLogK).

Finally I merge the n/k groups using a Merge Function(similar to Merging 
K Sorted arrays, complexity = nLog(n/k)).

So overall complexity is between nLogK and nLog(n/K) but I have to 
achieve complexity O(nLogK).
Comparing K and n/K depends on values of n and K.

任何人都可以帮助我进行最终的合并操作或更好的方法。

PS:我当时不知道堆或队列,因此我正在寻找不涉及这些的解决方案。

1 个答案:

答案 0 :(得分:4)

首先,将数组分成至少k+1个元素的组。这样,每个元素的合法位置要么在元素当前所在的组中,要么在左边或右边的组中,但不能更远。然后对每个组进行排序。

此步骤需要O((n/k) * k log k) = O(n log k)

然后,在对每个组进行排序之后,可以将第i个组与i+1组合并,将i1n/(k+1) - 1

通过合并,我从合并排序中了解了合并过程。这些团体不团结。它们的大小保持不变。

每个合并花费O(n/k),此步骤总计为O(n)