GeeksforGeeks » Algorithms

segregate 0 on left and 1 on right in 0(n)

(6 posts)
[closed]
  • Started 1 year ago by kapil
  • Latest reply from geeksforgeeks

Tags:

No tags yet.

  1. kapil
    guest
    Posted 1 year ago #

    an array of 0 and 1 in random order, segregate 0 on left and 1 on right in 0(n)

  2. Naveen
    guest
    Posted 1 year ago #

    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.

  3. kapil
    guest
    Posted 1 year ago #

    @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.

  4. Gautham
    Member
    Posted 1 year ago #

    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.

  5. Sandeep
    Moderator
    Posted 1 year ago #

    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;
    }
    
  6. GeeksforGeeks
    Key Master
    Posted 1 year ago #

    @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.

RSS feed for this topic