Tuesday, January 15, 2013

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


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

SOLUTION--


#include<stdio.h>
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;
}

2 comments:

  1. If you're only interested in the output and not actually sorting the array, it would be easier to just count the number of zeros (num_0s) and then print "num_0s" zeros and (num-num_0s) ones.

    ReplyDelete
  2. of course :)
    but above code used for arrange the all elements in array in sorted order.

    ReplyDelete