views:

147

answers:

3

Possible Duplicates:
How to sort in-place using the merge sort algorithm?
Regarding in-place merge in an array

Given an array of size N, which is divided into two sets of sorted integers(0 to P and P+1 to N-1). How would you sort this array using constant extra space (O(1)) and in O(n) time. For e.g

A = {1,3,5,7,2,4,6,8}, here N = 8, P = 3 and elements from 0 to 3 are sorted and elements from 4 to 7 are sorted.

Desired O/P: A = {1,2,3,4,5,6,7,8}

A: 

http://en.wikipedia.org/wiki/Radix_sort

Linear sorting time, no extra space required.

tsiki
have u read the question?
Ravi Gupta
which requirement doesn't radix sort fill?
tsiki
You don't know how big the numbers are, so technically radix sort is either not O(N) time or not O(1) memory, or not both. Assuming we're limited to 32 bit integers, then radix sort does fit all of the requirements.
IVlad
A: 

Your input array doesn't need to be sorted. You simply write out the numbers 0..N-1 (or 1..N your example is a bit confusing). I think you must have mis-stated your problem.

High Performance Mark
A: 

If I understand you correctly, you can allocate a new array to hold the result. So what you're doing is merging two sorted lists. A simple two-way merge does that nicely.

Jim Mischel
Allocating a new array to hold the result is an O(n) extra space operation which is disallowed by his constraints.
Mark Byers
`O(1)` space does not allow allocating a new array. All (known) solutions to this problem are freaking complex compared to the simplicity of the problem without the `O(1)` space constraint.
Daniel Brückner
I was confused by his wording. He said "O(1) extra space." The "extra" led me to believe that he could allocate a new array.
Jim Mischel