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

编程入门 行业动态 更新时间:2024-10-10 13:17:07
本文介绍了以O(n * Log(K))复杂度对几乎排序的数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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:我当时不知道堆或队列,因此我正在寻找一种不涉及这些的解决方案.

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

推荐答案

首先,将数组划分为至少包含k+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.

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

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

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.

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

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

更多推荐

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

本文发布于:2023-11-29 08:57:25,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1645934.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:复杂度   数组   Log

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!