The problem is taken from Elements of Programming Interviews:
Given an array A of n objects with Boolean-valued keys, reorder the array so that objects that have the
Let the array have 0 based index and let it have n
elements. Then you can do the following ( pseudo code below )
// A[] is your array
i = 0
k = 0
for i from 0 to n-1
if A[i] is true
swap A[i] and A[k]
increment k
Time complexity is O(n)
and extra space is only used for two variables i
and j
so memory is O(1)
. This way ordering is preserved amongst false and true values. ( This method puts true ones first you can change it according to your requirement ).