Friday, 16 November 2012

SORT THE ARRAY CONTAINING ONLY 0's AND 1's

Q.) SORT THE ARRAY CONTAINING ONLY 0's AND 1's .

SOLUTION--


#include
void swap(int *x,int *y)
{
        int temp;
        temp=*x;
        *x=*y;
        *y=temp;
        //return 0;
}
int main()
{
        int num,i,j;
        scanf("%d",&num);
        int arr[num];
        for(i=0;i<num;i++)
                scanf("%d",&arr[i]);
        for(i=0,j=num-1;i<=j;)
        {
                if(arr[i]==0)
                        i++;
                else{
                if(arr[j]==0)
                        swap(&arr[i],&arr[j]);
                j--;
                }
        }
        for(i=0;i<num;i++)
                printf("%d ",arr[i]);
        return 0;
}



solution by chris clerville (java) --
import java.util.Arrays;

public class SortZerosAndOnes {

static int[] sortZerosAndOnes(int[] a) {
if (a.length < 2) {
return a;
}
int len = a.length;
int sum = 0;

for(int i = 0 ; i < len ; i++) {
if(a[i] == 1) {
sum += a[i]; // The result will be the number of 1s in the array
a[i] = 0; // Make all the 1s zeros
}
}

// In reverse order place the 1s back into the array
for(int i = 0 ; i < sum ; i++) {
a[a.length-i-1] = 1;
}

return a;
}

public static void main(String[] args) {
int[] a = {0,1,0,1,0,1,1,0,1,0,0};
System.out.println(Arrays.toString(sortZerosAndOnes(a)));
// OUTPUT: [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1]
}
}

5 comments:

Girish Ponkiya said...

why such complicated program.!! It's very simple.

Just count no. of 0's and 1's, say it is m and n, respectively.
In array, set first m value to 0 and next m value to 1.

It's DONE.!!

CHANDAN SINGH said...

many methods are there to solve this question :)
anyway @girish nice solution.

Unknown said...

HERE IS MY SOLUTION :)

import java.util.Arrays;

public class SortZerosAndOnes {

static int[] sortZerosAndOnes(int[] a) {
if (a.length < 2) {
return a;
}
int len = a.length;
int sum = 0;

for(int i = 0 ; i < len ; i++) {
if(a[i] == 1) {
sum += a[i]; // The result will be the number of 1s in the array
a[i] = 0; // Make all the 1s zeros
}
}

// In reverse order place the 1s back into the array
for(int i = 0 ; i < sum ; i++) {
a[a.length-i-1] = 1;
}

return a;
}

public static void main(String[] args) {
int[] a = {0,1,0,1,0,1,1,0,1,0,0};
System.out.println(Arrays.toString(sortZerosAndOnes(a)));
// OUTPUT: [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1]
}
}

Raj said...

You can solve it in one pass using 2 pointers. Initially i points to 1 and j points to N. Increment i as long as a[i] is 0 and decrement j as long as a[j] is 1. Stop when a[i] is 1 and a[j] is 0. Exchange them and continue next.

CHANDAN SINGH said...

nice solution @raju sir :)
thnxx for the comment!!