Write a C program to segregate 0’s to the left and 1’s to the right of an array using Swapping method.
Related Read:
C Program To Segregate 0s and 1s In An Array using Counting Method
Page Contents
Example: Expected Input/Output
Enter 10 elements(0 or 1)
1
0
1
0
1
0
1
0
1
0
Array after sorting 0’s to left and 1’s to right
0
0
0
0
0
1
1
1
1
1
Visual Representation
Video Tutorial: C Program To Segregate 0’s and 1’s In An Array using Swapping Method
[youtube https://www.youtube.com/watch?v=AqJM2WtkeEU]
Source Code: C Program To Segregate 0’s and 1’s In An Array using Swapping Method
#include<stdio.h> #define N 5 int main() { int a[N], i, left = 0, right = N - 1; printf("Enter %d elements(0 or 1)\n", N); for(i = 0; i < N; i++) { scanf("%d", &a[i]); if(a[i] != 0 && a[i] != 1) { printf("Please enter only 0 and 1 as input\n"); i--; } } while(left < right) { while(a[left] == 0) left++; while(a[right] == 1) right--; if(left < right) { a[left++] = 0; a[right--] = 1; } } printf("\nArray after sorting 0's to left and 1's to right\n"); for(i = 0; i < N; i++) printf("%d\n", a[i]); printf("\n"); return 0; }
Output 1:
Enter 5 elements(0 or 1)
1
0
0
1
0
Array after sorting 0’s to left and 1’s to right
0
0
0
1
1
Output 2:
Enter 5 elements(0 or 1)
2
Please enter only 0’s and 1’s as input
10
Please enter only 0’s and 1’s as input
1
0
2
Please enter only 0’s and 1’s as input
1
1
0
Array after segregating o’s to left and 1’s to right
0
0
1
1
1
Logic To Segregate 0’s and 1’s In An Array using Swapping Method
We ask the user to input N integer numbers and store it inside a[N]. We assign 0(the first index of any array) to variable left and N – 1(the last index of any array) to variable right.
The outer while loop executes until left < right. Inside we write another while loop to check from left, if a[left] is 0. If its already 0, then its already in sorted order, so we don’t swap it. We simply increment the value of left by one position. Control exits this first inner while loop when a[left] is not equal to 0.
Similarly, we check if a[right] is 1. If its 1, we decrement the value of right by 1. When a[right] is not equal to 1, the control exits.
Now variable “left” will have the index position from left where there is number 1. And variable “right” will have the index position from right where there is number 0. Now we need to swap it.
We check if value of left is still less than the value of right. If true, we store 0 at a[left] and 1 at a[right].
Explanation With Example
If a[5] = {0, 1, 1, 0, 1};
left | a[left] | right | a[right] | Swap |
---|---|---|---|---|
0 | 0 | 4 | 1 | NO |
1 | 1 | 3 | 0 | YES |
2 | 1 | 2 | 1 | NO |
a[5] after sorting 0’s to left and 1’s to right:
a[5] = {0, 0, 1, 1, 1};
For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List
For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert