This is one of an interview question which I had recently. I would like to know others perception of approach for this problem.
Question:
Yo
Allocate a second array (O(N)). Iterate through first array and move all 1's in the order they appear to the second array. Iterate again and move the 0's that are left in the same order to the second array. All operations O(N). This is NOT in situ (in place) solution. A non-stable in situ solution is obtained by running the Quicksort partitioning algorithm once.
After conducting some research, it seems that the known O(N) solutions without any extra memory are not stable. There is academic research on efficient 0-1 stable sorting in situ (in place), but the solutions require some extra memory. I wonder if the original problem statement was not reproduced in an exact fashion. Without stability requirement the problem is very easy; it is also easy without in situ requirement. With BOTH of the requirements (in situ, stable) the solution seems to be elusive.
Among the answers here there is an algorithm that works in O(N) and is in situ, but only if the key field is (1) mutable and (2) can contain an integer instead of a single bit. This works but is not in situ 0-1 stable sorting, because it is assumed that there is O(log N) writable memory available per array element.
Easy:
function sort(array):
new_array = new Array(array.length)
x = 0
for(i : array): if(i): new_array(x++) = 1
return new_array
And if you actually want to have the same 1s and 0s:
function sort(array):
new_array = new Array(array.length)
x, y = 0, array.length / 2
for(i : array):
if(i): new_array(x++) = i
else: new_array(y++) = i
return new_array
It can be done in single pass and in place.
Ex: #include #define N 6 int main() { int list[N]={1,1,0,0,0,0}; int s,end,tmp; s=0;end=N-1;
while(s less than end)
{
if(list[s]==1)
{
while(list[end] == 1)
end--;
if(list[end] == 0 && s less than end)
{
tmp = list[s];
list[s] = list[end];
list[end] = tmp;
s++;end--;
}
}
else s++;
}
for(s=0;s less than N;s++)
{
printf("%d ",list[s]);
}
return;
}
What the heck, here is the whole solution:
arr is list of items, item.id is 0 or 1, stored as int.
This code moves the 0s to the front.
count = { 0:0, 1:len(arr)/2 }
for ii in range(len( arr )):
id = arr[ii].id
arr[ii].id = count[id]
count[id] += 1
for ii in range(len( arr )):
while arr[ii].id != ii:
T = arr[ii]
arr[ii] = arr[arr[ii].id]
arr[T.id] = T
for ii in range(len( arr )):
arr[ii].id = (ii >= len(arr)/2)
That'll be first step of radix sort.
left = 0;
right = n-1;
while(left<right){
while(left < right && array[left]==0){
left++;
}
while(left < right && array[right]==1){
right--;
}
while(left<right){
array[left]=0;
array[right]=1;
left++;
right--;
}
}