简体   繁体   中英

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+=2 if a[i] is smaller or j-=2 if a[j] is smaller. Need an extra array for that. Time is O(n) and space is 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?

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. A trivial improvement would be to use quicksort or merge sort and get an O(n log(n)) time complexity.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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