[英]Does sorting time of n numbers depend on a permutation of the numbers?
Consider this problem: 考虑这个问题:
A comparison-based sorting algorithm sorts an array with
n
items.基于比较的排序算法对具有
n
项目的数组进行排序。 For which fraction ofn!
对于
n!
哪个分数n!
permutations, the number of comparisons may becn
wherec
is a constant?排列,比较次数可能是
cn
其中c
是常数?
I know the best time complexity for sorting an array with arbitrary items is O(nlogn)
and it doesn't depend on any order, right? 我知道对具有任意项目的数组进行排序的最佳时间复杂度是
O(nlogn)
并且它不依赖于任何顺序,对吗? So, there is no fraction that leads to cn
comparisons. 因此,没有分数可导致
cn
比较。 Please guide me if I am wrong. 如果我错了,请指导我。
This depends on the sorting algorithm you use. 这取决于您使用的排序算法。
Optimized Bubble Sort for example, compares all neighboring elements of an array and swaps them when the left element is larger then right one. 例如, 优化的冒泡排序可比较数组的所有相邻元素,并在左侧元素大于右侧元素时交换它们。 This is repeated until no swaps where performed.
重复此操作,直到不执行任何交换为止。
When you give Bubble Sort a sorted array it won't perform any swaps in the first iteration and thus sorts in O(n). 当您为Bubble Sort提供排序后的数组时,它不会在第一次迭代中执行任何交换,因此会以O(n)进行排序。
On the other hand, Heapsort will take O(n log n) independent of the order of the input. 另一方面, Heapsort将获得O(n log n),而与输入顺序无关。
Edit: 编辑:
To answer your question for a given sorting algorithm, might be non-trivial. 要回答给定排序算法的问题,可能并非易事。 Only one out of n!
n中只有一个! permutations is sorted (assuming no duplicates for simplicity).
排列排序(为简单起见,假设没有重复项)。 However, for the example of bubblesort you could (starting for the sorted array) swap each pair of neighboring elements.
但是,以Bubblesort为例,您可以(从排序数组开始)交换每对相邻元素。 This input will take Bubblesort two iterations which is also O(n).
此输入将对Bubblesort进行两次迭代,这也是O(n)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.