Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Puzzle: Sort an array of 0's and 1's in one parse.

Is it possible to arrange the array made up of only 1's and 0's in descending order within one parse without using auxiliary array?
For example: Suppose you have an array a[]={1,0,0,0,1,0,1}, for this the expected output will be a[]={1,1,1,0,0,0,0}.

I have written the below C code but it finds the solution in 2 parses. Could it be optimized?

void arrange(int a[],int n) {
    int i,count=0;
    for(i=0;i<n;i++) {
            if(a[i]==1)
                    count++;
            a[i]=0;
    }
    for(i=0;i<count;i++) {
            a[i]=1;
    }
}
like image 889
prgmrDev Avatar asked Jul 27 '13 18:07

prgmrDev


People also ask

How do you sort an array with 0 and 1?

Given an integer array containing 0 and 1. We would like to sort input array. Zeros will be left end of array and one will be in right end of array. Suppose, we would like to sort an input array, as shown in Fig 1. After performing above algorithm, whole array will be sorted in O (n) times.

How to sort an array in Python?

Take two variables, low points zeroth index of array and high points to array’s length -1. After step 2, we will get the array as shown in Fig 4. We will repeatedly keep on perform step 2 till we get the sorted array.

How to traverse an array of 0s and 1s?

You are given an array of 0s and 1s in random order. Segregate 0s on left side and 1s on right side of the array [Basically you have to sort the array]. Traverse array only once. Recommended: Please solve it on “ PRACTICE ” first, before moving on to the solution. Thanks to Naveen for suggesting this method. 1) Count the number of 0s.

How to put 0 to the left side of an array?

Take two pointer type0 (for element 0) starting from beginning (index = 0) and type1 (for element 1) starting from end (index = array.length-1). 2. It is intended to Put 1 to the right side of the array. Once it is done, then 0 will definitely towards the left side of the array.


1 Answers

for (size_t i = 0, count = 0; i < n; i++) {
  if (a[i] == 1) a[count++] = 1;
  if (i >= count) a[i] = 0;
}
like image 116
nullptr Avatar answered Sep 29 '22 10:09

nullptr