Sorting complexity

170 views Asked by At

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?

1

There are 1 answers

4
Mureinik On

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