Segregate/sort 0s and 1s in an array
87 / 6
Write a program to sort an array containing only 0's and 1's in random order.
Answer:
#include
#include
using namespace std;
void segregate0and1(int arr[], int size)
{
int left = 0, right = size-1;
while (left < right)
{
while (arr[left] == 0 && left < right)
left++;
while (arr[right] == 1 && left < right)
right--;
if (left < right)
{
arr[left] = 0;
arr[right] = 1;
left++;
right--;
}
}
}
int main()
{
int arr[] = {0, 1, 0, 1, 1, 1};
int i, arr_size = sizeof(arr)/sizeof(arr[0]);
segregate0and1(arr, arr_size);
cout
Asked In ::
Language:
Vishal Rai
7 Jul, 2017 9:30 AM
#include<stdio.h>
/*Function to put all 0s on left and all 1s on 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--;
}
}
}
/* driver program to test */
int main()
{
int arr[] = {0, 1, 0, 1, 1, 1};
int i, arr_size = sizeof(arr)/sizeof(arr[0]);
segregate0and1(arr, arr_size);
printf("Array after segregation ");
for (i = 0; i < 6; i++)
printf("%d ", arr[i]);
getchar();
return 0;
}
Language:
Disha
7 Jul, 2017 9:30 AM
#include<stdio.h>
#include <iostream>
using namespace std;
void segregate0and1(int arr[], int size)
{
int left = 0, right = size-1;
while (left < right)
{
while (arr[left] == 0 && left < right)
left++;
while (arr[right] == 1 && left < right)
right--;
if (left < right)
{
arr[left] = 0;
arr[right] = 1;
left++;
right--;
}
}
}
int main()
{
int arr[] = {0, 1, 0, 1, 1, 1};
int i, arr_size = sizeof(arr)/sizeof(arr[0]);
segregate0and1(arr, arr_size);
cout<<"Array after segregation ";
for (i = 0; i < 6; i++)
cout<< arr[i];
getchar();
return 0;
}
Language:
Siddhartha Paul
19 Jun, 2019 2:16 PM
import java.util.*;
public class Sorting
{
public static void main(String []args)
{
int i,j,temp,f=0;
Scanner sc=new Scanner(System.in);
System.out.println("Enter the range of the array: ");
int n=sc.nextInt();
int a[]=new int[n];
System.out.println("Enter the numbers in 0's and 1's: ");
for(i=0;i<n;i++)
{
a[i]=sc.nextInt();
}
for(i=0;i<n-1;i++)
{
for(j=0;j<n-i-1;j++)
{
if((a[j]<a[j+1]) && (a[j]==0 || a[j]==1) && (a[j+1]==0 || a[j+1]==1))
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
if(a[j]>=a[j+1])
continue;
else
{
f=1;
break;
}
}
}
if(f==1)
System.out.println("Wrong input of numbers");
else
{
System.out.println("Sorted order: ");
for(i=0;i<n;i++)
{
System.out.print(a[i]+" ");
}
}
}
}