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.
/*
* C Program to Segregate 0s on Left Side & 1s on right side of the Array (Traverse Array only once)
*/
#include <stdio.h>
/*Function to segregate all 0s on left and all 1s on right*/
void segregate0and1(int array[], int size)
{
int left = 0, right = size-1;
while (left < right)
{
/* Increment left index while we see 0 at left */
while (array[left] == 0 && left < right)
left++;
/* Decrement right index while we see 1 at right */
while (array[right] == 1 && left < right)
right--;
/* If left is smaller than right then there is a 1 at left and a 0 at right. Exchange it */
if (left < right)
{
array[left] = 0;
array[right] = 1;
left++;
right--;
}
}
}
int main()
{
int arr[] = {0, 1, 0, 1, 1, 0};
int array_size = 6, i = 0;
segregate0and1(arr, array_size);
printf("segregated array is ");
for (i = 0; i < 6; i++)
printf("%d ", arr[i]);
getchar();
return 0;
}
$ 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]Related Posts:
- Apply for Computer Science Internship
- Watch Advanced C Programming Videos
- Apply for C Internship
- Practice BCA MCQs
- Check C Books