Sorting nearly sorted array with O(n*Log(K)) complexity

落花浮王杯 提交于 2019-12-10 10:57:36

问题


Problem -Nearly Sorted Array- Given an array of n elements , each of which is atmost K Position away from it's actual position in the sorted array , devise an algorithm that sorts in O(nLogK) time.

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.

Can anyone help me with the final merging operation or a better approach.

PS : I do not know heaps or queues at the time so I am looking for a solution which does not involve these.


回答1:


First, divide the array into groups of at least k+1 elements. So that each element's rightful position is either within the group where the element currently is or within the group to the left or to the right, but not further. Then sort each group.

This step takes O((n/k) * k log k) = O(n log k).

Then, after sorting each group, you can merge ith group with the i+1 group, for i from 1 to n/(k+1) - 1.

By merge I understand the merge procedure from a merge sort. The groups do not unite. Their sizes remain the same.

Each merge takes O(n/k), in total this step is O(n).



来源:https://stackoverflow.com/questions/55615707/sorting-nearly-sorted-array-with-onlogk-complexity

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