1

if I have an array with cells 0-N that sorted, and cells N+1 until M+N, not sorted. what will be the best time complexity to sort the array?

thanks!


Edit:

thanks !! If I want to do that in-place, it will change the complexity?

1
  • 1
    O((m+n) log (m+n)). If you use a standard library function, this bound is exact, and you can't get much better anyways. Commented Feb 2, 2013 at 0:24

1 Answer 1

4

First, sort just the M unsorted elements. This takes time O(M log M) using a comparison-based sort (like quicksort, merge sort, or heap sort).

Then merge the two sorted segments (of lengths N and M) together. This takes time O(M + N).

So the best time complexity, using a comparison-based sorted, is O(M + N + M log M).

Sign up to request clarification or add additional context in comments.

5 Comments

M is the size of the unsorted part
Yes, I realized that I misread the problem and fixed my solution.
Note that O(M + M log M)=O(M log M), meaning that you can simplify the complexity expression.
thanks !! If I want to do that in-place, it will change the complexity?
If you can merge two sorted arrays in linear time and constant additional space, you won't change the complexity. This paper claims to describe such an algorithm, but I've only read the abstract.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.