1

I have an array of objects. the objects have a Boolean value in them that I want to use as a key for sorting the array (all objects with true come before all objects with false) but otherwise leave things in the same order.

Is there a simple, in-place, O(n) solution to this? Maybe some variant of radix-sort?

3
  • Here's another very similar question stackoverflow.com/questions/682171/arrange-0s-1s-in-a-array Commented Apr 2, 2009 at 6:24
  • there is a slight difference in that question though, in that you are given that half the elements are 1's and half are 0's, which can help you either reduce space or time requirements a bit Commented Apr 2, 2009 at 6:36
  • Well, that's reasonable. Commented Apr 2, 2009 at 6:38

3 Answers 3

5

See here for a discussion on this topic. You can basically have either an O(n)-solution which needs additional space or a O(n log n) in-place solution.

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

Comments

0

Merge sort. O(n log n).

Comments

0

Hmm. With a linked list it should be feasible - you'd search for the first "false" entry and keep it as the "insertion location". (If there are no "false" entries then you're done anyway :) Then just iterate through the whole list - if you're before the insertion location and find a "false" entry or if you're after the insertion location and find a "true" entry then move it to directly before the "insertion location". So far, so O(n).

Now you can convert an array into a linked list in O(n) and you can copy the data back into the array in O(n). So I think it would work in terms of complexity - but it's not in-place. I'll think about whether it can be done in-place...

Comments

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.