GeeksforGeeks » Algorithms
segregate 0 on left and 1 on right in 0(n)
(6 posts)-
an array of 0 and 1 in random order, segregate 0 on left and 1 on right in 0(n)
-
loop through the array and find out how many 0's and 1's are present. Let's say number of 0's are M and number of 1's are N. Modify the first M elements of the array to 0 and the rest to 1.
-
@Naveen
I suggested the same approac in my interview, but interviewer asked me to do it in single pass.I missed to mention it in my original question.
-
You can maintain a queue containing position of 1's. If you encounter a 0 and the queue is non empty, pop a position from the queue, modify its value to 0, modify the current position value as 1 and push it to the queue.
-
Maintain two indexes. Initialize first index left as 0 and second index right as n-1.
Keep on incrementing left index while there are 0s at it
Keep on decrementing right index while there are 1s at it
Now if left < right then exchange arr[left] and arr[right]void segregate0and1(int arr[], int size) { /* Initialize left and right indexes */ int left = 0, right = size-1; while(left < right) { /* Increment left index while we see 0 at left */ while(arr[left] == 0 && left < right) left++; /* Decrement right index while we see 1 at right */ while(arr[right] == 1 && left < right) right--; /* If left is smaller than right then there is a 1 at left and a 0 at right. Exchange arr[left] and arr[right]*/ if(left < right) { arr[left] = 0; arr[right] = 1; left++; right--; } } } int main() { int arr[] = {0, 1, 0, 1, 1, 1}; int arr_size = 6, i = 0; segregate0and1(arr, arr_size); printf("array after segregation "); for(i = 0; i < 6; i++) printf("%d ", arr[i]); getchar(); return 0; } -
@kapil and @Naveen: This has been published.
Please see http://geeksforgeeks.org/?p=5234
Thanks for your contribution to the portal. Keep it up!!
Topic Closed
This topic has been closed to new replies.