简体   繁体   English

排序复杂性

[英]Sorting complexity

Given an array where values in the even indices are in incremental and values that in odd indices are in decremental order. 给定一个数组,其中偶数索引中的值是递增的,而奇数索引中的值是递减顺序。 For example: 例如:

[1,99,16,65,45,23,97]

I have thought about two different ways of sorting this: 我想过两种不同的排序方法:

  1. Starting from i=0, j=a.length-2 and comparing values of a[i] with a[j]. 从i = 0开始,j = a.length-2并且将a [i]的值与a [j]进行比较。 i+=2 if a[i] is smaller or j-=2 if a[j] is smaller. 如果a [i]较小,则i + = 2;如果[j]较小,则i = = 2。 Need an extra array for that. 需要一个额外的阵列。 Time is O(n) and space is O(n). 时间是O(n),空间是O(n)。

  2. Reversing the order of the elements where their index is odd, and then bubble sort the entire array. 颠倒其索引为奇数的元素的顺序,然后对整个数组进行冒泡排序。 Space is O(1).. what about the time? 空间是O(1)..时间怎么样?

Which is more efficient? 哪个更有效率? What is the worst case time and space complexity for each? 每种情况的最坏情况时间和空间复杂度是多少? The bubble sort can takes a lot longer, no? 冒泡排序可能需要更长时间,不是吗?

I have yet to see a good use case for bubble sort in a real-world scenario. 在现实世界的场景中,我还没有看到泡泡排序的一个很好的用例。 If you're going with option two, once you flip the cells in the odd indexes you have an array that may or may not be sorted on it's own right, and apply an O(n 2 ) bubble sort. 如果您使用选项2,一旦您在奇数索引中翻转单元格,您就有一个可能或可能不会对其进行排序的数组,并应用O(n 2 )冒泡排序。 A trivial improvement would be to use quicksort or merge sort and get an O(n log(n)) time complexity. 一个微不足道的改进是使用快速排序或合并排序并获得O(n log(n))时间复杂度。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM