简体   繁体   English

n个数字的排序时间是否取决于数字的排列?

[英]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 of n! 对于n!哪个分数n! permutations, the number of comparisons may be cn where c 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.

相关问题 查找数字1到N的排列,以使排列之间的任何两个数字均不出现平均值 - Find a permutation of numbers 1 through N such that average of any two numbers in the permutation does not occur between them 在 O(n) 时间内对 (1,2,3) 个数字的数组进行排序 - sorting array of (1,2,3) numbers in O(n) time 在线性时间内对 0 到 n^2 – 1 范围内的 n 个数字进行排序 - Sorting n numbers in range from 0 to n^2 – 1 in linear time 迭代范围为 0..n 且 n 大的数字的随机排列 - Iterate over a random permutation of numbers in the range 0..n with large n 迭代地生成自然数的排列 - Iteratively generating a permutation of natural numbers Swift中O(log n)时间的中间数 - Middle numbers in O(log n) time in Swift 3sum在n ^ 2 * log(n)时间中有4个数字的变体? - Variant of 3sum with 4 numbers in n^2*log(n) time? 在恒定时间内使用n ^ 2个处理器查找n个数的最小值 - Finding minimum of n numbers with n^2 processors in constant time 找到一个线性时间算法,该算法对间隔[0,2]中的n个数字进行排序,使得每2个数字a,b:| ab | >(1 / n)^ 2 - Find a linear time algorithm that sorts n numbers from the interval [0,2] such that for each 2 numbers a,b : |a-b| > (1/n)^2 生成一系列数字范围内的所有置换的序列 - Generate a sequence of all permutation of some range of numbers
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM