C Program to Segregate 0s and 1s in an Array

This C Program segregates 0s on left side & 1s on right side of the array.

Here is source code of the C Program to segregate 0s on left side & 1s on right side of the array. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C Program to Segregate 0s on Left Side & 1s on right side of the Array (Traverse Array only once)
  3.  */
  4. #include <stdio.h>
  5.  
  6. /*Function to segregate all 0s on left and all 1s on right*/
  7. void segregate0and1(int array[], int size)
  8. {
  9.     int left = 0, right = size-1;
  10.  
  11.     while (left < right)
  12.     {
  13.         /* Increment left index while we see 0 at left */
  14.         while (array[left] == 0 && left < right)
  15.             left++;
  16.         /* Decrement right index while we see 1 at right */
  17.         while (array[right] == 1 && left < right)
  18.             right--;
  19.         /* If left is smaller than right then there is a 1 at left and a 0 at right.  Exchange it */
  20.         if (left < right)
  21.         {
  22.             array[left] = 0;
  23.             array[right] = 1;
  24.             left++;
  25.             right--;
  26.         }
  27.     }
  28. }
  29.  
  30. int main()
  31. {
  32.     int arr[] = {0, 1, 0, 1, 1, 0};
  33.     int array_size = 6, i = 0;
  34.  
  35.     segregate0and1(arr, array_size);
  36.     printf("segregated array is ");
  37.     for (i = 0; i < 6; i++)
  38.         printf("%d ", arr[i]);
  39.     getchar();
  40.     return 0;
  41. }

$ cc pgm96.c
$ a.out
segregated array is 0 0 0 1 1 1

Sanfoundry Global Education & Learning Series – 1000 C Programs.

advertisement
advertisement

Here’s the list of Best Books in C Programming, Data-Structures and Algorithms

If you wish to look at other example programs on Arrays, go to C Programming Examples on Arrays. If you wish to look at programming examples on all topics, go to C Programming Examples.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.